日期:2014-05-20 浏览次数:20725 次
public class GoogleJsonTest {
public static void main(String[] args) {
Gson gson = new Gson();
Object myValue = new MyValue("9527", 999.99);
// 对象转为json // String jsonStr = convertObjectToString(myValue);
String jsonStr = gson.toJson(myValue);
System.out.println(jsonStr + myValue.getClass());
// json字符串转为对象
MyValue myValue2 = gson.fromJson(jsonStr, MyValue.class);// 这个应该是你想要的操作吧
System.out.println(myValue2);
System.out.println(myValue == myValue2);
List<Object> myValueList = new ArrayList<Object>();
myValueList.add(myValue);
myValueList.add("111");
myValueList.add(myValue2);
String jsonStrValues = gson.toJson(myValueList);
System.out.println("jsonStrValues===" + jsonStrValues);
List<Object> myValueList2 = gson.fromJson(jsonStrValues, List.class);// 有告警
for (Object obj : myValueList2) {
System.out.println("obj is===" + obj+":"+obj.getClass());
}
}
}
// 这个是我自定义的一个简单的类,LZ需要自己定义一个类,有Name和Chinese属性
class MyValue {
private String id;
private double price;
private Detail detail;
public MyValue(String id, double price) {
this.id = id;
this.price = price;
this.detail = new Detail("我的ID是:" + id + "。很高兴认识大家!");
}
@Override
public String toString() {
return "id:" + id + ";price:" + price + ";宣言:" + detail.getMyWords();
}
private class Detail {
private String myWords;
public Detail(String myWords) {
this.myWords = myWords;
}
public String getMyWords() {
return myWords;
}
}
}
package com.armslee.json.test.model;
import java.io.Serializable;
public class Grade implements Serializable{
/**
*
*/
private static final long serialVersionUID = -2118483800595534815L;
private String chinese;
private String math;
private String english;