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

后端 未结 2 501
旧巷少年郎
旧巷少年郎 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条回答
  • 2020-11-27 06:03

    I think BalusC gave good pointers for the specific question wrt GSon (and in general, one-to-one data binding); but just in case you think there should be more dynamic handling, you could also consider other JSON processing packages. Many packages have additional or alternative ways to map things: Json-lib, flexjson and Jackson at least have additions compared to Gson. Some offer looser mapping (you define names of things to types), others actual support for polymporphic types (declaring an Object but can actually map to subtype that was serialized).

    0 讨论(0)
  • 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<Node> 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.

    0 讨论(0)
提交回复
热议问题