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

Parse JSON(with subJson) without java subobjects

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

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



但是,从 "address" 我只需要 "city"。我如何在不创建新的 class(对于 lib.GSON)的情况下做到这一点?
我尝试使用 JsonPath,但我无法理解如何将 JsonObject "address" 替换为字符串值 "city".

给你

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

试试

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

我想我理解你的问题是正确的:你想用 /address/city 替换 /address,这样

{
  "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\"")))

您可以为 JSONFactory:

使用依赖注入
@Inject
JSONFactory JSON;

选项 B:相反,您可以与 it.bewares JSON 结合使用 it.bewares JSONPatch. JSON补丁是提议的标准(参见维基百科RFC 6902

一个有效的 JSON 补丁应该是:

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

使用 it.bewares 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);

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