JavaGSON将json序列化为对象

JavaGSON将json序列化为对象,java,json,gson,Java,Json,Gson,我有以下项目类别: public class Item { public Object item; } 我使用GSON将JSON插入到这个对象中 tmp= { "_id": { "$oid": "5076371389d22e8906000000" }, "item": { "values": [ { "value1": [ 4958,

我有以下项目类别:

public class Item {
    public Object item;
}
我使用GSON将JSON插入到这个对象中

tmp=

{
    "_id": {
        "$oid": "5076371389d22e8906000000"
    },
    "item": {
        "values": [
            {
                "value1": [
                    4958,
                    3787,
                    344
                ],
                "value2": [
                    4,
                    13,
                    23
                ]
            }
        ], 
        "name": "item1"
    }
}
Java位:

Item item = new Item();
Gson g = new Gson();
it = g.fromJson(tmp.toString(), Item.class);
it.item
成为
StringMap
类型()

我现在需要访问此对象中的子对象。 我可以使用此类型具有的重写
toString
函数打印此对象中的所有对象。但我如何才能在其中导航呢? 另外,我之所以将所有内容都放在对象数据类型而不是结构化类中,是因为JSON结构每次都会变化,所以我不能真正拥有一个类模式。
有什么建议吗?

您应该创建一个反映JSON的对象结构(因为这正是您要做的)。例如,您可以使用以下方法:

public class MyObject {
    private Item item;
    private String _id;

    // getters, setters, etc.
}

public class Item {
    private List<Value> values;
    private String name;

    // getters, setters, etc.
}

public class Value {
    private List<Integer> values1;
    private List<Integer> values2;

    // getters, setters, etc.
}
您可以在
值中获得列表,如下所示:

List<Integer> values1 = myObj.getItem().getValues().get(0).getValues1();
List<Integer> values2 = myObj.getItem().getValues().get(0).getValues2();
List values1=myObj.getItem().getValues().get(0.getValues1();
列表值2=myObj.getItem().getValues().get(0.getValues2();
试试看它是否有效


另外,您应该查看我对一个类似问题的回答,特别是最后关于如何基于某个JSON对象为Gson编写对象结构的部分。

您始终可以为使用反射并采用StringMap的自定义对象创建构造函数

public MyObject(StringMap sm){
    Iterator it = sm.entrySet().iterator();
    while(it.hasNext()){
        Entry pairs = (Entry)it.next();
        Class<?> c = this.getClass();
        try {
            Field value = c.getDeclaredField((String) pairs.getKey());
            value.set(this, pairs.getValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
公共MyObject(StringMap sm){
迭代器it=sm.entrySet().Iterator();
while(it.hasNext()){
Entry pairs=(Entry)it.next();
c类=this.getClass();
试一试{
字段值=c.getDeclaredField((字符串)pairs.getKey());
set(this,pairs.getValue());
}捕获(例外e){
e、 printStackTrace();
}
}
}

啊,对不起,我没看到你问题的结尾。JSON结构的变化有多大?它是从非结构化数据集生成的。唯一保持不变的是Item对象。
public MyObject(StringMap sm){
    Iterator it = sm.entrySet().iterator();
    while(it.hasNext()){
        Entry pairs = (Entry)it.next();
        Class<?> c = this.getClass();
        try {
            Field value = c.getDeclaredField((String) pairs.getKey());
            value.set(this, pairs.getValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}