Java 使用“键”和“值”属性反序列化 JSON 映射不适用于 Jackson

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20701082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:40:04  来源:igfitidea点击:

Deserializing JSON map with "key" & "value" properties does not work with Hymanson

javaandroidjsonserializationHymanson

提问by joelpet

Questions

问题

  1. To begin with, does the serialized JSON serialization below make sense?
  2. If so, why am I not getting the Map back?
  3. What can I do about it on the deserializing side?
  1. 首先,下面的序列化 JSON 序列化有意义吗?
  2. 如果是这样,为什么我没有取回地图?
  3. 在反序列化方面我能做些什么?

JSON serialization of Map<String, String> property (excerpt):

Map<String, String> 属性的 JSON 序列化(摘录):

{
  "attributes": {
    "entry": [
      {
        "key": "operating system",
        "value": "GNU/Linux"
      },
      {
        "key": "allergies",
        "value": "weed"
      }
    ]
  }
}

POJO for deserialization:

用于反序列化的 POJO:

class Contact implements Comparable<Contact>, Serializable {
    @JsonProperty("attributes")
    private Map<String, String> attributes;
    ...
}

Causes this exception:

导致此异常:

Thread-4889 An exception occurred during request network execution :Could not read JSON: Can not deserialize instance of java.lang.String out of START_ARRAY token
            at [Source: libcore.net.http.FixedLengthInputStream@43822760; line: 1, column: 17] (through reference chain: com.example.model.Contact["attributes"]); nested exception is com.fasterxml.Hymanson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token
            at [Source: libcore.net.http.FixedLengthInputStream@43822760; line: 1, column: 17] (through reference chain: com.example.model.Contact["attributes"])
    org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of java.lang.String out of START_ARRAY token
            at [Source: libcore.net.http.FixedLengthInputStream@43822760; line: 1, column: 17] (through reference chain: com.example.model.Contact["attributes"]); nested exception is com.fasterxml.Hymanson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token
            at [Source: libcore.net.http.FixedLengthInputStream@43822760; line: 1, column: 17] (through reference chain: com.example.model.Contact["attributes"])
            at org.springframework.http.converter.json.MappingHymanson2HttpMessageConverter.readInternal(MappingHymanson2HttpMessageConverter.java:126)
            at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:147)
            at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:76)
            at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:484)
            at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:439)
            at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:237)
            at com.example.providers.Query.loadDataFromNetwork(Query.java:99)
            at com.octo.android.robospice.request.CachedSpiceRequest.loadDataFromNetwork(CachedSpiceRequest.java:45)
            at com.octo.android.robospice.request.RequestRunner.processRequest(RequestRunner.java:130)
            at com.octo.android.robospice.request.RequestRunner.run(RequestRunner.java:197)
            at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:390)
            at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: com.fasterxml.Hymanson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token
            at [Source: libcore.net.http.FixedLengthInputStream@43822760; line: 1, column: 17] (through reference chain: com.example.model.Contact["attributes"])
            at com.fasterxml.Hymanson.databind.DeserializationContext.mappingException(DeserializationContext.java:691)
            at com.fasterxml.Hymanson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:46)
            at com.fasterxml.Hymanson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11)
            at com.fasterxml.Hymanson.databind.deser.std.MapDeserializer._readAndBindStringMap(MapDeserializer.java:430)
            at com.fasterxml.Hymanson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:312)
            at com.fasterxml.Hymanson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:26)
            at com.fasterxml.Hymanson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:525)
            at com.fasterxml.Hymanson.databind.deser.impl.FieldProperty.deserializeAndSet(FieldProperty.java:106)
            at com.fasterxml.Hymanson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:242)
            at com.fasterxml.Hymanson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:118)
            at com.fasterxml.Hymanson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:227)
            at com.fasterxml.Hymanson.databind.deser.std.CollectionDeserializer.des

The attributes Object when inspected in debugger after deserialization:

反序列化后在调试器中检查的属性对象:

Deserialized Object inspected in debugger

Deserialized Object inspected in debugger

Further inspection after changing to:

改成后进一步检查:

@JsonProperty("attributes")
private Map<String, List<Map<String, String>>> attributes;

attributes.entrySet()attributes.get("entry")

attributes.entrySet()attributes.get("entry")

Dependencies:

依赖项:

  • com.fasterxml.Hymanson.core:Hymanson-core:2.3.0
  • com.fasterxml.Hymanson.core:Hymanson-databind:2.3.0
  • com.fasterxml.Hymanson.core:Hymanson-annotations:2.3.0
  • com.fasterxml.Hymanson.core:Hymanson-core:2.3.0
  • com.fasterxml.Hymanson.core:Hymanson-databind:2.3.0
  • com.fasterxml.Hymanson.core:Hymanson-annotations:2.3.0

采纳答案by Maxim Shoustin

If we will convert Mapto json:

如果我们将转换Map为 json:

    Map<String, String> map = new HashMap<String, String>();
    map.put("operating system", "GNU/Linux");
    map.put("allergies", "weed");

The output will be:

输出将是:

{"operating system":"GNU/Linux","allergies":"weed"}

As we can see there is no key/value.

正如我们所见,没有key/value.

Solution

解决方案

WrapperObject

包装对象

@JsonIgnoreProperties(ignoreUnknown = true)
public class WrapperObject { // we can give any name to class, its only external {}    

    private Attributes attributes;

    public WrapperObject() {}

    public Attributes getAttributes() {
        return attributes;
    }    
}

Attributes

属性

@JsonIgnoreProperties(ignoreUnknown = true)  
public class Attributes {

    public Attributes() {}

    private ArrayList<Entry> entry;  

    public ArrayList<Entry> getEntry() {
        return entry;
    }    
}

Entry

入口

@JsonIgnoreProperties(ignoreUnknown = true)    
public  class Entry {

    private String key;
    private String value;


    public Entry() {}


    public String getKey() {
        return key;
    }


    public String getValue() {
        return value;
    }
}

Launcher

启动器

public static void main(String[] args) throws JsonParseException, JsonMappingException,     IOException {
    String str = "{" + 
            "  \"attributes\": {" + 
            "    \"entry\": [" + 
            "      {" + 
            "        \"key\": \"operating system\"," + 
            "        \"value\": \"GNU/Linux\"" + 
            "      }," + 
            "      {" + 
            "        \"key\": \"allergies\"," + 
            "        \"value\": \"weed\"" + 
            "      }" + 
            "    ]" + 
            "  }" + 
            "}";



    ObjectMapper mapper = new ObjectMapper();
    WrapperObject mj = mapper.readValue(str, WrapperObject.class);

    if(mj == null){
        System.err.println("null");
    }
    // dummy check
    System.out.println(mj.getAttributes().getEntry().get(0).getKey());
}

Output:

输出:

operating system