简体   繁体   English

在Java中使用GSON从嵌套Json提取JSONObjects数组

[英]Extract Array of JSONObjects from a nested Json using GSON in java

I have a nested JSON object in which one of the nested objects (keyed parameters ) is an unknown object itself. 我有一个嵌套的JSON对象,其中一个嵌套对象(键parameters )是一个未知对象本身。 The only known part is that it's an array of further objects. 唯一已知的部分是它是其他对象的数组。

The problem is that the contents of this object are completely unknown(dynamic) and so I can't define a class with some known variable names for it. 问题在于该对象的内容是完全未知的(动态的),因此我无法为其定义具有某些已知变量名称的类。

What I need to achieve is to extract and store all these dynamic key-value pairs. 我需要实现的是提取并存储所有这些动态键值对。 For example in the below code, for parameters I need to extract both alpha and then its contents type , and store them as a Map . 例如,在下面的代码中,对于parameters我需要同时提取alpha和其内容type ,并将它们存储为Map

js is the JSON I'm trying to parse into my class NestedJsonParse . js是我要解析为我的类NestedJsonParse

public class NestedJsonParse {
    String name;
    Experiment experiment;
    Parameters parameters;

    NestedJsonParse(String name, Experiment experiment, Parameters parameters) {
        this.name = name;
        this.experiment = experiment;
        this.parameters = parameters;
    }

    public String getName() { return name; }

    public String getExpName() { return experiment.getName(); }

    public String getParams() { return parameters.getParamsAsStrings(); }

    @Override
    public String toString() {
        return "NSP{" +
            "name='" + getName() + '\'' +
            ", exp-name='" + getExpName() + '\'' +
            ", params='" + getParams() + '\'' +
            "========================================"  +
            "}";
    }

    public class Experiment {
        String name;

        Experiment(String name) {
            this.name = name;
        }

        public String getName() { return name; }
    }

    public class Parameters {
        List<JSONObject>  parameters;

        Parameters(List<JSONObject> parameters) {
            this.parameters = parameters;
        }

        public String getParamsAsStrings() {
            return "abc";
        }
    }

    public static void main(String[] args) throws Exception {
        String js = "{\"name\" : \"e0\", \"experiment\" : { \"name\" : \"e1\" },  \"parameters\" : [ {\"alpha \": { \"type\" : \"float\" } } ]  }";

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(js);  // Passes

        Gson GSON = new GsonBuilder().create();
        NestedJsonParse nsp = GSON.fromJson(js, NestedJsonParse.class);  // Fails
        System.out.println("NSP : " + nsp.toString());
    }
}

This passes if the JSON does not contain a parameters block but fails otherwise with this error: 如果JSON不包含parameters块,则失败,否则失败,并显示以下错误:

Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 206 path $.parameters 由以下原因引起:java.lang.IllegalStateException:预期为BEGIN_OBJECT,但在行1列206路径$ .parameters处为BEGIN_ARRAY

One simple option is just to deserialize parameters as an Object so no class Parameters at all. 一个简单的选择就是将parameters反序列化为一个Object这样就根本没有类Parameters Your NestedJsonParse could (greatly simplified) be like: 您的NestedJsonParse可以(大大简化)如下:

@Getter @Setter
public class NestedJsonParse {
    private String name;
    private Experiment experiment;
    private Object parameters;
}

Then when you do 那当你做

NestedJsonParse nsp = GSON.fromJson(js, NestedJsonParse.class);

your parameters in nsp could be: 您在nspparameters可能是:

  • null 空值
  • com.google.gson.internal.LinkedTreeMap com.google.gson.internal.LinkedTreeMap
  • ArrayList containing above mentioned or other ArrayList etc... 包含上面提到的ArrayList或其他ArrayList等...

depending on what is in the JSON. 取决于JSON中的内容。

Based on what you find from parameters you can take appropriate action after deserialization. 根据从parameters找到的内容,可以在反序列化之后采取适当的措施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM