How to unwrap single item array and extract value field into one simple field?

前端 未结 2 706
无人及你
无人及你 2021-01-23 01:28

I have a JSON document similar to the following:

{
  \"aaa\": [
    {
      \"value\": \"wewfewfew\"
    }
  ],
  \"bbb\": [
    {
      \"value\": \"wefwefw\"
          


        
2条回答
  •  渐次进展
    2021-01-23 01:31

    For completeness, if you use jackson, you can enable the deserialization feature UNWRAP_SINGLE_VALUE_ARRAYS. To do that, you have to enable it for the ObjectMapper like so:

    ObjectMapper objMapper = new ObjectMapper()
        .enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
    

    With that, you can just read the class as you are being used to in Jackson. For example, assuming the class Person:

    public class Person {
        private String name;
        // assume getter, setter et al.
    }
    

    and a json personJson:

    {
        "name" : [
            "John Doe"
        ]
    }
    

    We can deserialize it via:

    ObjectMapper objMapper = new ObjectMapper()
        .enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
    
    Person p = objMapper.readValue(personJson, Person.class);
    

提交回复
热议问题