【问题标题】:JSON parsing for dynamic schema using DropWizard使用 DropWizard 对动态模式进行 JSON 解析
【发布时间】:2015-12-18 11:11:47
【问题描述】:

我需要解析JSON,动态模式命中我们的API,我需要做出相应的响应。

动态模式就像,

{
"query": {
    <OPERATOR>: {
        <FIELD>: <VALUE>
    }
},
"fields" : [<FIELD_1>, <FIELD_2>, ...],
"from": 0,
"size": 10
}

{
"query": {
    "and": [
        {
            <OPERATOR>: { 
                <FIELD>: <VALUE> 
            }
        },
        {
            <OPERATOR>: {
                    <FIELD>: <VALUE>
                }
        }
    ]
},
"fields" : [<FIELD_1>, <FIELD_2>, ...],
"from": 0,
"size": 10
}

我们的回复将基于上述JSON's。每个JSON 类型的响应都会不同。 我可以使用 dropwizard 的 Jackson 库来解析还是需要编写自己的解析器是两难的。如果是,怎么做?

提前致谢。

【问题讨论】:

  • 这很容易做到,但我只能在 GSON 中做到这一点
  • 太棒了!在 GSON 中,当某些键丢失时如何处理?很多检查会让它看起来很糟糕,对吧?所以,它正在编写自己的解析器!
  • @是的,您是对的,如果您丢失了密钥,那么您将能够获得它的相应价值。要使用 Gson,您应该具有有效的 JSON 格式
  • 可以是数组还是对象??有可能吗?
  • 对,可以是对象也可以是数组。所以,我无法预料。

标签: java json web-services jackson dropwizard


【解决方案1】:

如果您卡在我的代码中,请告诉我,因为我没有时间完善它。

String result = response.toString();
    Object mainResponse = null;
    try {
        mainResponse = new JSONTokener(result).nextValue();
        if (mainResponse instanceof JSONArray) {
            JSONArray json1 = new JSONArray(response.toString());
            Object value2 = json1.get(0);
            Object output = tryMethod((JSONObject) value2, searchString);
            outputtv.setText(output.toString());
            Log.i("Output", output.toString() + "");
        }
        if (mainResponse instanceof JSONObject) {
            JSONObject json = new JSONObject(response.toString());
            Object output1 = tryMethod(json, searchString);
            outputtv.setText(output1.toString());
            Log.i("Output", output1 + "");
        }

    } catch (JSONException e1) {
        e1.printStackTrace();
    }

【讨论】:

    猜你喜欢
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    相关资源
    最近更新 更多