我正在尝试使用gson将JSON字符串读入Java程序。在下面的示例代码中- Java程序具有3个对象类。json字符串中的数据将具有可变数量的每个类的对象实例。我试图创建一个示例JSON-来解析..但在解析各种对象时遇到了问题。
这是使用json字符串的正确方法还是可以通过其他方式完成呢。您将如何使用不同类的可变对象解析json。谢谢,
package newpackage; import java.util.ArrayList; import com.google.gson.Gson; public class jsonsample { public static void main(String[] args) { String jsonstring = "{'TableA':[{'field_A1':'A_11'},{'field_A1':'A_12'}]}" + ",{'TableB':[{'field_B1':'B_11','field_B2':'B_12','field_B3':['abc','def','ghi']}," + "{'field_B1':'B_21','field_B2':'B_Field22','field_B3':['mno','pqr','xyz']}]" + ",{'TableC':[{'field_C1':'C_11','field_C2':'C_12','field_C3':'C_13'}," + "{'field_C1':'C_21','field_C2':'C_22','field_C3':'C_23'},{'field_C1':'C_31','field_C2':'C_32','field_C3':'C_33'}]}"; jsonstring = jsonstring.replace('\'', '"'); } public class TableA { String field_A1; public TableA(String a){ this.field_A1 = a; } @Override public String toString() { return ("Table A" + " " + this.field_A1); } } public class TableB { String field_B1; String field_B2; ArrayList<String> field_B3 = new ArrayList<String>(); public TableB(String a, String b, ArrayList<String> c){ this.field_B1 = a; this.field_B2 = b; this.field_B3 = c; } @Override public String toString() { return ("Table B" + " " + this.field_B1+ " " + this.field_B2); } } public class TableC { String field_C1; String field_C2; String field_C3; public TableC(String a, String b, String c){ this.field_C1 = a; this.field_C2 = b; this.field_C3 = c; } @Override public String toString() { return ("Table C" + " " + this.field_C1 + " " + this.field_C2 + " " + this.field_C3); } }
}
首先,您必须确定您的基本json结构是什么?最大标识符,最大值,最大对象,最大数组…
让我们认为这是我完整的json结构:
{ "array": [ 1, 2, 3 ], "boolean": true, "null": null, "number": 123, "object": { "a": "b", "c": "d", "e": "f" }, "string": "Hello World" }
这些是我的Java类:
public class Object { public string a { get; set; } public string c { get; set; } public string e { get; set; } } public class RootObject { public ArrayList<int> array { get; set; } public Boolean boolean { get; set; } public Object @null { get; set; } public int number { get; set; } public Object @object { get; set; } public string @string { get; set; } }
对于Java;
String data = "jsonString"; RootObject root = new GsonBuilder().create().fromJson(data, RootObject.class);
对于杰森;
Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy").create(); String json = gson.toJson(obj);