How do I use Google's Gson API to deserialize JSON properly?

后端 未结 2 515
旧巷少年郎
旧巷少年郎 2020-11-27 05:07

In short, this is a sketch of the JSON object I want to parse in JAVA:

{
    object1: {
            item1: //[String | Array | Object] ,
            item2: /         


        
2条回答
  •  -上瘾入骨i
    2020-11-27 06:10

    That's not possible. You need to modify your JSON structure to represent object1, object2, etc as items of an array. Right now they are properties of an object of which it's apparently unknown how many of them will be (else you didn't attempt to map it as a List). Gson is smart, but not that smart :)

    So, as a basic example, this JSON structure with an array:

    { nodes:
      [
        { item1: 'value1a', item2: 'value2a' },
        { item1: 'value1b', item2: 'value2b' },
        { item1: 'value1c', item2: 'value2c' }
      ]
    }
    

    in combination with the Java representation (which is not necessarily to be called POJO, but just javabean or model object or value object).

    public class Container {
        private List nodes;
        // +getter.
    }
    
    public class Node {
        private String item1;
        private String item2;
        // +getters.
    }
    

    and this Gson call

    Container container = new Gson().fromJson(json, Container.class);
    

    should work.

    Update: to be clear, your JSON structure is the problem, not your Java object structure. Assuming that your Java object structure is exactly what you would like to end up with, then your JSON structure should look like follows to get Gson to do its job:

    { jObjects:
      [
        { id: 123, jObjects: 
          [
            { item1: 'value1a', item2: 'value2a' },
            { item1: 'value1b', item2: 'value2b' },
            { item1: 'value1c', item2: 'value2c' }
            /* etc... commaseparated */
          ]
        },
        { id: 456, jObjects: 
          [
            { item1: 'value1d', item2: 'value2d' },
            { item1: 'value1e', item2: 'value2e' },
            { item1: 'value1f', item2: 'value2f' }
            /* etc... commaseparated */
          ]
        }
        /* etc... commaseparated */
      ]
    }
    

    Only the JsonElement property should be replaced by String, since it's invalid.

提交回复
热议问题