【问题标题】:Jackson map deserialization - value replacement杰克逊地图反序列化 - 值替换
【发布时间】:2016-10-11 21:14:11
【问题描述】:

反序列化这个 Json 对象的最佳方法是什么?

{
    "key1" : "val1",
    "key2" : "blank"
}

进入一个java hashmap,其中字符串blanknull替换?

   {
        "key1" : "val1",
        "key2" : null
   }

我目前正在使用 Jackson 进行反序列化。

【问题讨论】:

  • 您可以尝试实现自己的 JsonDeserializer,然后通过 new SimpleModule().addSerializer(YourClass.class, new YourDeserializer()); 为您的类添加此序列化器,在对象映射器上注册该模块。查看 JsonCodec.treeToValue 以找到放置替换逻辑的位置。

标签: java json jackson deserialization


【解决方案1】:

你会找到部分答案here

您只需要在 while 循环中操作该行:

Object value;
if (object.get(key).equals("blank")) {
    value = "null";
} else {
    value = object.get(key);
}

打印出来会给出:

System.out.println(map.get("key1")); // returns val1
System.out.println(map.get("key2")); // returns null

您的最终代码将如下所示,您可能需要导入正确的 .jar 文件:

import com.orsoncharts.util.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static com.sun.xml.internal.ws.binding.WebServiceFeatureList.toList;

public class JsonAnswerOne {

    public static void main(String[] args) throws JSONException {

        String input = "{\n" +
                "    \"key1\" : \"val1\",\n" +
                "    \"key2\" : \"blank\"\n" +
                "}";

        parse(input);
    }

    private static void parse(String input) throws JSONException {
        JSONObject mainObject = new JSONObject(input);
        Map<String, Object> map = jsonToMap(mainObject);
        System.out.println(map.get("key1")); // returns val1
        System.out.println(map.get("key2")); // returns null
    }

    private static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if (json != JSONObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }

    private static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keys();
        while (keysItr.hasNext()) {
            String key = keysItr.next();
            Object value;
            if (object.get(key).equals("blank")) {
                value = "null";
            } else {
                value = object.get(key);
            }

            if (value instanceof JSONArray) {
                value = toList((JSONArray) value);
            } else if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }

}

【讨论】:

    【解决方案2】:

    我试过this,结果是这样的:

    // use of the deserializer
    String json = "{\"key1\":\"val1\",\"key2\":\"blank\"}";
    ObjectMapper mapperMap = new ObjectMapper();
    SimpleModule moduleMap = new SimpleModule();
    moduleMap.addDeserializer(Map.class, new MapDeserializer());
    mapperMap.registerModule(moduleMap);
    Map map = mapperMap.readValue(json, Map.class);
    
    // custom deserializer
    public class MapDeserializer extends StdDeserializer<Map<String, String>> {
    
        public MapDeserializer() {
            this(null);
        }
    
        public MapDeserializer(Class<?> vc) {
            super(vc);
        }
    
        @Override
        public Map<String, String> deserialize(JsonParser jp, DeserializationContext context)
                throws IOException {
            // definitely not the best way but it works...
            Map<String, String> map = new HashMap<>();
            String[] keys = new String[] {"key1", "key2"};
    
            JsonNode node = jp.getCodec().readTree(jp);
            String value;
            for (String key : keys) {
                value = node.get(key).asText();
                if (value.equals("blank")) {
                    value = null;
                }
                map.put(key, value);
            }
            return map;
        }
    }
    

    完整的示例解决方案以及将 JSON 反序列化为另一个类的附加示例:
    https://gist.github.com/audacus/e70ce0f3cd4b17197d911769e05b237e

    【讨论】:

      猜你喜欢
      • 2012-01-11
      • 1970-01-01
      • 2014-02-21
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 2017-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多