package com.codebonneamie.demo;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
private void convertToJson()
{
Country country = new Country();
List<Language> languages = new ArrayList<Language>();
Language language = null;
country.setName( “India” );
language = new Language();
language.setName( “Hindi” );
language.setFamily( “Indo-European” );
languages.add( language );
language = new Language();
language.setName( “Tamil” );
language.setFamily( “Dravidian” );
languages.add( language );
country.setLanguages( languages );
Gson gson = new Gson();
String jsonString = gson.toJson( country );
System.out.println( “jsonString: ” + jsonString );
Country c = gson.fromJson( jsonString, Country.class );
System.out.println( c );
}
…
class Country
{
private String name;
private List<Language> languages;
public String getName()
{
return name;
}
public void setName( String name )
{
this.name = name;
}
public List<Language> getLanguages()
{
return languages;
}
public void setLanguages( List<Language> languages )
{
this.languages = languages;
}
@Override
public String toString()
{
return “Country [name=” + name + “, languages=” + languages + “]”;
}
}
class Language
{
private String name;
private String family;
public String getName()
{
return name;
}
public void setName( String name )
{
this.name = name;
}
public String getFamily()
{
return family;
}
public void setFamily( String family )
{
this.family = family;
}
@Override
public String toString()
{
return “Language [name=” + name + “, family=” + family + “]”;
}
}