//Direct Initialization
Gson gson = new Gson();
//or
//we can set our formatting options
Gson gson = new GsonBuilder()
.disableHtmlEscaping()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.setPrettyPrinting()
.serializeNulls()
.create();
យើងអាចបោះតំលៃរបស់អថេរដោយផ្ទាល់(អាចជាobject or primitives),ដែលនឹងត្រូវបំលែងទៅជាjson format.តែវាជាបញ្ហាា គឹដោយសារវាមិនមែនជាkey value pair.
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
Gson gson=new Gson();
String name="itjontot";
System.out.println(gson.toJson(name));
}
}
output:
"itjontot" //expected format is {"name":"itjontot"}
តោះបង្កើត Employee class ដែលមាន name និង age ដែលជា data members ហើយបង្កើត setters និង getters method។ បន្ទាប់មក បង្កើត employee object ហើយ pass ទៅgson ដើម្បីបបំលែងពីjava objectទៅជា json format។
Employee class
public class Emp {
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public Emp(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Emp() {
super();
}
public void setAge(int age) {
this.age = age;
}
}
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
Gson gson=new Gson();
Emp emp=new Emp("Sok",25);
System.out.println(gson.toJson(emp));
}
}
output:
{"name":"Sok","age":25}
ខាងក្រោមជាការបំលែងទិន្នន័យពី JSON format ទៅជា Java Object វិញ។ជាជំហានដំបូងបង្កើត gson objectរួចហើយ fromJson method របស់ gson oject ដោយ បោះjson data និង matching class របស់ data ហ្នឹង។
import com.google.gson.Gson;
public class ReverseJson {
public static void main(String[] args)
{
Gson gson = new Gson();
Emp emp=gson.fromJson("{'name':'Dara','age':25}",
Emp.class);
System.out.println(emp.getName());
}
}
output:
Dara