JSON formatting for a Java Server

后端 未结 3 837
自闭症患者
自闭症患者 2021-01-26 23:55

I am trying to read JSON string using gson into a Java program. In the sample code below - the Java program has 3 object classes. The data in the json string will have a vari

3条回答
  •  星月不相逢
    2021-01-27 00:30

    First of all you have to decide what is your base json structure ? Max identifiers, max values, max objects,max arrays...

    1. Create your full json structure with texteditor or http://www.jsoneditoronline.org/ or http://jsonlint.com/ etc.

    Let's think this is my full json structure:

    {
      "array": [
        1,
        2,
        3
      ],
      "boolean": true,
      "null": null,
      "number": 123,
      "object": {
        "a": "b",
        "c": "d",
        "e": "f"
      },
      "string": "Hello World"
    }
    
    1. Create your Java Classes as like as your json identifiers. You can use http://json2csharp.com/ convert to Java.

    And these are my Java Classes:

    public class Object
    {
        public string a { get; set; }
        public string c { get; set; }
        public string e { get; set; }
    }
    
    public class RootObject
    {
        public ArrayList 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; }
    }
    
    1. Create your DAO for convert these to structure to them.

    For Java;

    String data = "jsonString"; 
    RootObject root = new GsonBuilder().create().fromJson(data, RootObject.class);
    

    For Json;

    Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy").create();
    String json = gson.toJson(obj);
    

提交回复
热议问题