用Jackson反序列化为Map <string,string =“”>

时间:2018-01-02 11:52:26

标签: java json jackson

我有以下JSON:

{
  "parameters": [{
      "value": "somevalue",
      "key": "somekey"
    },
    {
      "value": "othervalue",
      "key": "otherkey"
    }
  ]
}

请注意,此响应的合同保证密钥是唯一的。

我想将其分解为以下类:

public class Response {

  public Map<String, String> parameters;

}

我如何使用杰克逊图书馆这样做?

3 个答案:

答案 0 :(得分:4)

您需要注册反序列化器:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Response.class, new ResponseDeserializer());
mapper.registerModule(module);

Response resp = mapper.readValue(myjson, Response.class);

以下是一个例子:

public class ResponseDeserializer extends StdDeserializer<Response> {
    public ResponseDeserializer() { 
        this(null); 
    } 

    public ResponseDeserializer(Class<?> vc) { 
        super(vc); 
    }

    @Override
    public Response deserialize(JsonParser jp, DeserializationContext dc)
            throws IOException, JsonProcessingException {
        Response resp = new Response();
        resp.parameters = new HashMap<>();
        JsonNode node = jp.getCodec().readTree(jp);
        ArrayNode parms = (ArrayNode)node.get("parameters");
        for (JsonNode parm: parms) {
            String key = parm.get("key").asText();
            String value = parm.get("value").asText();
            resp.parameters.put(key, value);
        }
        return resp;
    }   
}

答案 1 :(得分:2)

您需要custom deserializer

答案 2 :(得分:0)

您可以将JSON更改为以下内容吗?

activity.ChannelId == ChannelEnum.webchat.ToString()

如果是这样,反序列化应该在没有任何自定义反序列化器的情况下进行。

(参考:https://blog.hackingcode.io/jackson-java-tutorial-deserialize-json-to-map/