解析没有java子对象的JSON(带有subJson)

时间:2018-01-22 08:29:57

标签: java json parsing gson jsonpath

我如何解析像这样的json字符串:

{
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 26,
  "address"  : {
    "streetAddress": "naist street",
    "city"         : "Nara",
    "postalCode"   : "630-0192"
  }
}



但是,从"地址" 我只需要" city" 。如何在不创建新类的情况下实现它(对于lib.GSON)? 我尝试使用JsonPath,但我不明白如何替换JsonObject"地址" to String value" city"。

3 个答案:

答案 0 :(得分:0)

你去吧

try {
        JSONObject jsonObject=new JSONObject(jsonString);
        JSONObject address=jsonObject.getJSONObject("address");
        String city=address.getString("city");
    } catch (JSONException e) {
        e.printStackTrace();
    }

答案 1 :(得分:0)

尝试类似

的内容
DocumentContext ctx = JsonPath.parse("your-json-here");
YourPojoHere pojo = new YourPojoHere(
   ctx.read("$.firstName"),
   ctx.read("$.lastName"),
   ctx.read("$.age"),
   ctx.read("$.address.city"));

答案 2 :(得分:0)

我想我理解你的问题是正确的:你想用/address取代/address/city,以便

{
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 26,
  "address"  : {
    "streetAddress": "naist street",
    "city"         : "Nara",
    "postalCode"   : "630-0192"
  }
}

然后

{
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 26,
  "address"  : "Nara"
}

选项A :您可以使用it.bewares JSON,然后使用JSON选择器就可以了:

JSONFactory JSON = new JSONFactory(SimpleJSONParser.class, SimpleJSONGnerator.class);

String input = "{\"firstName\":\"John\",\"lastName\":\"doe\",\"age\":26,\"address\":{\"streetAddress\":\"naist street\",\"city\":\"Nara\",\"postalCode\":\"630-0192\"}}";
JSONValue json = JSON.parse(input);

json.put("address", JSON.find(new JSONSelector(".\"address\".\"city\"")))

您可以将Dependecy Injection用于JSONFactory:

@Inject
JSONFactory JSON;

选项B :您可以将it.bewares JSONPatchWikipedia结合使用。 JSON补丁是一个建议的标准(见RFC 6902,{{3}})

有效的JSON补丁将是:

[
  { "op": "move", "from": "/address/city", "path": "/address" }
]

使用it.bewares JSONPatch它将是:

JSONFactory JSON = new JSONFactory(SimpleJSONParser.class, SimpleJSONGnerator.class);

String input = "{\"firstName\":\"John\",\"lastName\":\"doe\",\"age\":26,\"address\":{\"streetAddress\":\"naist street\",\"city\":\"Nara\",\"postalCode\":\"630-0192\"}}";
JSONValue json = JSON.parse(input);

String patchString = "[{\"op\":\"move\",\"from\":\"/address/city\",\"path\":\"/address\"}]";
JSONPatch patch = new JSONPatch(JSONArray<JSONObject<JSONString>> JSON.parse(patchString));
JSONPatch.execute(patch, json);