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

前端 未结 2 691
无人及你
无人及你 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: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 {
        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);
      }
    
    }
    

提交回复
热议问题