如何使用 Google 的 Gson API 正确反序列化 JSON? [英] How do I use Google's Gson API to deserialize JSON properly?

查看:24
本文介绍了如何使用 Google 的 Gson API 正确反序列化 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之,这是我要在 JAVA 中解析的 JSON 对象的草图:

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

{
    object1: {
            item1: //[String | Array | Object] ,
            item2: // ...
            //<> more items
    object2: { /* .. */ }
    //<> more objects
}

这些是我为解析而创建的 POJO(为简洁起见,我将省略 import 语句):

These are the POJO s I created for parsing (I'll leave out the import statements for brevity's sake):

(1) 完整JSON对象的表示

(1) The representation of the complete JSON object

public class JObjectContainer {

    private List<JObject> jObjects ;

    public JObjectContainer() { }

    //get & set methods

}

(2)嵌套对象的表示:

(2) The representation of the nested objects:

 public class JObject {

    private String id ;
    private List<JNode> jObjects ;

    public JObject() { } 

    //get & set methods

}

(3) 物品的表示:

 public class JNode {

    private JsonElement item1 ;
    private JsonElement item2 ;
    //<> more item fields

    public JNode() { }

    //get & set methods

}

现在,创建一个 Gson 实例(FileReader 用于导入 jsonFile),

Now, creating a Gson instance (FileReader for importing the jsonFile),

 Gson gson = new Gson() ;
 JObjectContainer joc = gson.fromJson(jsonFile,JObjectContainer.class) ;

每当我尝试访问可解析对象(例如通过 ListIterator)时,我都会收到 NullPointerException.Gson确实创建了一个我指定的类的对象,并且不会抛出任何后续错误.

I get a NullPointerException whenever I try to access the parseable object (e.g. through a ListIterator). Gson does however create an object of the class I specified and does not throw any subsequent errors.

我知道以前已经这样做了.那么,我错过了什么?

I know that this has been done before. So, what am I missing?

TIA

推荐答案

那是不可能的.您需要修改 JSON 结构以将 object1object2 等表示为 array 的项目.现在它们是一个对象的属性,显然不知道它们有多少(否则你没有尝试将它映射为 List).Gson 很聪明,但不是那个聪明 :)

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 :)

所以,作为一个基本的例子,这个带有数组的 JSON 结构:

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

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

结合 Java 表示(不一定称为 POJO,而只是 javabean 或模型对象或值对象).

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.
}

还有这个 Gson 调用

and this Gson call

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

应该可以.

更新:需要明确的是,问题在于您的 JSON 结构,而不是您的 Java 对象结构.假设您的 Java 对象结构正是您想要的结果,那么您的 JSON 结构应如下所示以让 Gson 完成其工作:

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 */
  ]
}

只有 JsonElement 属性应该被替换为 String,因为它是无效的.

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

这篇关于如何使用 Google 的 Gson API 正确反序列化 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆