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

前端 未结 2 689
无人及你
无人及你 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);
    
    0 讨论(0)
  • 2021-01-23 01:45

    Quick solution with Gson is to use a JsonDeserializer like this:

    package stackoverflow.questions.q17853533;
    
    import java.lang.reflect.Type;
    
    import com.google.gson.*;
    
    public class MyEntityDeserializer implements JsonDeserializer<MyEntity> {
        public MyEntity deserialize(JsonElement json, Type typeOfT,
            JsonDeserializationContext context) throws JsonParseException {
    
        String aaa = json.getAsJsonObject().getAsJsonArray("aaa").get(0)
            .getAsJsonObject().get("value").getAsString();
        String bbb = json.getAsJsonObject().getAsJsonArray("bbb").get(0)
            .getAsJsonObject().get("value").getAsString();
    
        return new MyEntity(aaa, bbb);
        }
    }
    

    and then use it when parsing:

    package stackoverflow.questions.q17853533;
    
    import com.google.gson.*;
    
    public class Q17853533 {
    
    
      public static void main(String[] arg) {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(MyEntity.class, new MyEntityDeserializer());
    
        String testString = "{        \"aaa\": [{\"value\": \"wewfewfew\"  } ],  \"bbb\": [  {\"value\": \"wefwefw\" } ]    }";
    
    
        Gson gson = builder.create();
        MyEntity entity= gson.fromJson(testString, MyEntity.class);
        System.out.println(entity);
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题