如何在将JSON解析为映射时忽略特定字段

sag*_*sag 5 java json jackson

我想将下面的JSON解析为POJO.我用杰克逊来解析json.

{
  "totalSize": 4,
  "done": true,
  "records": [
    {
      "attributes": {
        "type": "oppor",
        "url": "/service/oppor/456"
      },
      "AccountId": "123",
      "Id": "456",
      "ProposalID": "103"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

在上面的JSON中,字段"totalSize","done","records"和"attributes"是已知字段.鉴于"AccountId","Id"和"ProposalID"是未知字段.在上面的JSON中,我不需要"属性"成为我的bean对象的一部分.

这里是我的JSON的等效bean类

public class Result {
    private int totalSize;
    private boolean done;
    private List<Map<String, String>> records;

    public int getTotalSize() {
        return totalSize;
    }

    public void setTotalSize(int totalSize) {
        this.totalSize = totalSize;
    }

    public boolean isDone() {
        return done;
    }

    public void setDone(boolean done) {
        this.done = done;
    }

    public List<Map<String,String>> getRecords() {
        return records;
    }

    public void setRecords(List<Map<String, String>> records) {
        this.records = records;
    }

}
Run Code Online (Sandbox Code Playgroud)

因此,我刚刚使用List记录元素中有未知字段来获取bean中的结果元素.在这个Map中,我不希望字段"属性".解析时如何忽略这一点?以下是我得到的例外,因为属性不是字符串元素.

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: [B@66fdec9; line: 1, column: 40] (through reference chain: com.sample.json.Result["records"])
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164)
    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:691)
    at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:46)
    at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringMap(MapDeserializer.java:430)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:312)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:26)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:227)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:204)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:23)
Run Code Online (Sandbox Code Playgroud)

BNK*_*BNK 4

2015/08/29 更新:

正如你所评论的那样

我通过将 JSON 解析为映射来实现动态字段支持。忽略错误的 JSON 元素是待处理的

我建议您应该处理原始 JSONObject 以"attributes"从中删除元素。

原始JSONObject,例如:

{
  "totalSize": 4,
  "done": true,
  "records": [
    {
      "attributes": {
        "type": "oppor",
        "url": "/service/oppor/456"
      },
      "AccountId": "123",
      "Id": "456",
      "ProposalID": "103"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

处理后,新的 JSONObject 将如下所示:

{
    "records": {
        "AccountId": "123",
        "Id": "456",
        "ProposalID": "103"
    },
    "totalSize": 4,
    "done": true
}
Run Code Online (Sandbox Code Playgroud)

使用代码如下:

        JSONObject jsonObject;
        try {            
            jsonObject = new JSONObject(jsonString1);
            JSONArray jsonArray = new JSONArray(jsonObject.get("records").toString());            
            JSONObject jsonObject1 = jsonArray.getJSONObject(0);
            jsonObject1.remove("attributes");
            jsonObject.put("records", jsonObject1);
        } catch (JSONException e) {
            e.printStackTrace();
        }
Run Code Online (Sandbox Code Playgroud)

然后,使用您自己的代码achieved dynamic field support by parsing the JSON into map

更新结束 2015/08/29

我建议您在这种情况下使用Gsonandtransient

像这样

        String jsonString1 = "{\n" +
                "  \"totalSize\": 4,\n" +
                "  \"done\": true,\n" +
                "  \"records\": [\n" +
                "    {\n" +
                "      \"attributes\": {\n" +
                "        \"type\": \"oppor\",\n" +
                "        \"url\": \"/service/oppor/456\"\n" +
                "      },\n" +
                "      \"AccountId\": \"123\",\n" +
                "      \"Id\": \"456\",\n" +
                "      \"ProposalID\": \"103\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        Gson gson = new Gson();
        Result result1 = gson.fromJson(jsonString1, Result.class);
Run Code Online (Sandbox Code Playgroud)

您的课程,请注意transient

public class Result {
    private int totalSize;
    private boolean done;
    private List<Record> records;
}

public class Record {
    private transient Map<String, String> attributes;
    private int AccountId;
    private int Id;
    private int ProposalID;
}
Run Code Online (Sandbox Code Playgroud)

你会得到结果:

在此输入图像描述

P/S:我在 Android Studio 中测试过:)

更新:

      String jsonString1 = "{\n" +
                "  \"totalSize\": 4,\n" +
                "  \"done\": true,\n" +
                "  \"records\": [\n" +
                "    {\n" +
                "      \"attributes\": {\n" +
                "        \"type\": \"oppor\",\n" +
                "        \"url\": \"/service/oppor/456\"\n" +
                "      },\n" +
                "      \"AccountId\": \"123\",\n" +
                "      \"Id\": \"456\",\n" +
                "      \"ProposalID\": \"103\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";
        Gson gson = new Gson();
        Object object = gson.fromJson(jsonString1, Object.class);
        Map<String, String> stringMap = (Map<String, String>) object;
        Result myResult = new Result();
        Iterator entries = stringMap.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            String key = entry.getKey().toString();
            String value = entry.getValue().toString();
            switch (key) {
                case "totalSize":
                    myResult.totalSize = (int) Double.parseDouble(entry.getValue().toString());
                    break;
                case "done":
                    myResult.done = Boolean.valueOf(entry.getValue().toString());
                    break;
                case "records":
                    try{
                        Object object1 = entry.getValue();
                        List<Object> objectList = (List<Object>) object1;
                        Map<String, Object> stringMap2 = (Map<String, Object>) objectList.get(0);
                        Map<String, String> recordMap = new HashMap<>();
                        Iterator entries2 = stringMap2.entrySet().iterator();
                        while (entries2.hasNext()) {
                            Map.Entry entry2 = (Map.Entry) entries2.next();
                            String key2 = entry2.getKey().toString();
                            String value2 = entry2.getValue().toString();
                            if (!"attributes".equals(key2)) {
                                recordMap.put(key2, value2);
                            }
                            entries2.remove();
                        }
                        myResult.records = recordMap;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
            entries.remove();
        }
Run Code Online (Sandbox Code Playgroud)

课程:

public class Result {
    private int totalSize;
    private boolean done;
    private Map<String, String> records;        
}
Run Code Online (Sandbox Code Playgroud)

调试结果:

在此输入图像描述