???? 可以直接执行如下类中的main方法将json字符串转换为相应对象后并打印出转换后的对象:
?
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
*
* @author Josh Wang(Sheng)
*
* @email josh_wang23@hotmail.com
*/
public class JsonBean {
private String a;
private List<B> b; // array
private C c;
private Map<String, String> d;
public class B {
private String b1;
private String b2;
public String getB1() {
return b1;
}
public void setB1(String b1) {
this.b1 = b1;
}
public String getB2() {
return b2;
}
public void setB2(String b2) {
this.b2 = b2;
}
}
public class C {
public String c1;
public String c2;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public List<B> getB() {
return b;
}
public void setB(List<B> b) {
this.b = b;
}
public C getC() {
return c;
}
public void setC(C c) {
this.c = c;
}
public Map<String, String> getD() {
return d;
}
public void setD(Map<String, String> d) {
this.d = d;
}
@Override
public String toString() {
return "JsonBean [a=" + a + ", b=" + b.get(0).getB2() + ", c=" + c.c2 + ", d=" + d.get("myKey") +"]";
}
public static void main(String[] args) {
String json = "{\"a\":\"100\",\"b\":[{\"b1\":\"b_value1\",\"b2\":\"b_value2\"},{\"b1\":\"b_value1\",\"b2\":\"b_value2\"}],"
+ "\"c\":{\"c1\":\"c_value1\",\"c2\":\"c_value2\"}, \"d\": {\"myKey\":\"myValue\"} }";
GsonBuilder builder = new GsonBuilder();
// builder.setDateFormat(DateUtils.MIDDLE_LINE_TIMESTAMP);
// builder.registerTypeAdapter(NucleonEventType.class, new NucleonEventTypeSerializer());
Gson gson = builder.create();
System.out.println(gson.fromJson(json, JsonBean.class));
}
}
?
执行结果为:
JsonBean [a=100, b=b_value2, c=c_value2, d=myValue]
?
?
?
