每种原始数据类型的JSON至Map <string>转换

时间:2019-05-15 09:15:04

标签: java json jackson

此代码的目的是将未知数量的参数和未知数量的值转换为<input class="my-datepicker" id="from_date" type="text" placeholder="From" name="from_date" value=""> <script> $(window).on('load', function() { $.when( $.getScript( "https://cdnjs.cloudflare.com/ajax/libs/pikaday/1.8.0/pikaday.min.js" ), $.Deferred(function( deferred ){ $( deferred.resolve ); }) ).done(function(){ $(".my-datepicker").pikaday({ firstDay: 1 }); }) }); </script> (键-参数名称,值-可能的参数值列表),假设每种类型都会解析到字符串。

问题在于数字和其他格式未解析为String,并且Map<String, List<String>>不是值节点jsonField.getValue()返回jsonField.getValue().isValueNode()),所以我无法使用false,因为它返回了jsonField.getValue().asText()

我的方法:

null

输入:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections4.map.ListOrderedMap;

public ListOrderedMap<String, ArrayList<String>> convertParamsFromJson(String jsonParams) throws IOException {

    ListOrderedMap<String, ArrayList<String>> convertedParams = new ListOrderedMap<>();
    Iterator<Entry<String, JsonNode>> fieldsFromJson = convertFromJson(jsonParams).fields();
    ObjectMapper mapper = new ObjectMapper();

    while (fieldsFromJson.hasNext()) {
        Entry<String, JsonNode> jsonField = fieldsFromJson.next();
        String paramName = jsonField.getKey();
        String paramValue = jsonField.getValue();
        if (jsonField.getValue().isArray()) {
            convertedParams.put(paramName, mapper.convertValue(paramValue, ArrayList.class));
        }
    }

    return convertedParams;
}

预期输出:

{
"firstParam":[1],
"secondParam": ["a","b","c","d"],
"thirdParam": [1,2,3],
"fourthParam":[true,false]
}

输出:

  <[MapEntry[key="firstparam", value=["1"]],
    MapEntry[key="secondparam", value=["a","b","c","d"]],
    MapEntry[key="thirdparam", value=["1","2","3"]],
    MapEntry[key="fourthparam", value=["true", "false"]]]>

1 个答案:

答案 0 :(得分:1)

默认情况下,Jackson库将JSON基元转换为合适的类型。考虑以下示例:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.Map;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        String json = "{\"firstParam\":[1],\"secondParam\": [\"a\",\"b\",\"c\",\"d\"],\"thirdParam\": [1,2,3],\"fourthParam\":[true,false]}";

        ObjectMapper mapper = new ObjectMapper();
        Map<String, List<Object>> map = mapper.readValue(json, Map.class);
        map.forEach((k, v) -> {
            System.out.print(k + " => ");
            v.forEach(i -> System.out.print(i + " (" + i.getClass().getSimpleName() + "), "));
            System.out.println();
        });
    }
}

上面的代码显示:

firstParam => 1 (Integer), 
secondParam => a (String), b (String), c (String), d (String), 
thirdParam => 1 (Integer), 2 (Integer), 3 (Integer), 
fourthParam => true (Boolean), false (Boolean), 

但是我们可以通过使用String提供我们需要实现的类型来强制将列表项转换为TypeReference

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        String json = "{\"firstParam\":[1],\"secondParam\": [\"a\",\"b\",\"c\",\"d\"],\"thirdParam\": [1,2,3],\"fourthParam\":[true,false]}";

        TypeReference<LinkedHashMap<String, List<String>>> mapOfStringListsType = new TypeReference<LinkedHashMap<String, List<String>>>() {};
        ObjectMapper mapper = new ObjectMapper();
        Map<String, List<String>> map = mapper.readValue(json, mapOfStringListsType);
        map.forEach((k, v) -> {
            System.out.print(k + " => ");
            v.forEach(i -> System.out.print(i + " (" + i.getClass().getSimpleName() + "), "));
            System.out.println();
        });
    }
}

上面的代码显示:

firstParam => 1 (String), 
secondParam => a (String), b (String), c (String), d (String), 
thirdParam => 1 (String), 2 (String), 3 (String), 
fourthParam => true (String), false (String), 
相关问题