使用GSON解析混合类型字段?

时间:2014-09-20 15:48:39

标签: java android json gson

如何将GSON与混合类型字段一起使用,是否可能?

{
  'field': false
}

// or

{
  'field': [
    1,2,3,4
  ]
}

我的GSON课程:

public class MyModel {

    public  HashMap<ArrayList,Boolean>  blockedusers;

}

2 个答案:

答案 0 :(得分:1)

是的,但是如果json是数组或基本类型,则必须处理。尝试下面的代码:

String case1 = "{'field':false}";
String case2 = "{'field':[1,2,3,4]}";
JsonElement jsonElement = ((JsonObject)(new JsonParser().parse(case1))).get("field");

if(jsonElement instanceof JsonArray) {
    JsonArray jsonArray = (JsonArray)jsonElement;
    if(jsonArray != null && jsonArray.size() > 0) {
        for (JsonElement aJsonElement : jsonArray) {
            // TODO: handle json element inside array 
            System.out.println(aJsonElement);
        }
    }
} else if (jsonElement instanceof JsonPrimitive) {
    boolean value = jsonElement.getAsBoolean();
    System.out.println("value:" + value);
}

您也可以编写自定义TypeAdapter。见my answer for another question

答案 1 :(得分:0)

正如GSON parsing unspecified type variable

中所述

我认为你必须定义一个自定义反序列化器:

        public class MyJsonDeserializer implements JsonDeserializer<YourParsedData> {

       @Override 
       public YourParsedData deserialize(final JsonElement je, final Type type, final JsonDeserialization Context jdc) throws JsonParseException
       {
          final JsonObject obj = je.getAsJsonObject(); //our original full json string
          final JsonElement serviceElement = obj.get("field");


         //here we provide the functionality to handle the naughty element. It seems emtpy string is returned as a JsonPrimitive... so one option
         if(serviceElement instanceOf JsonPrimitive)
         {
//get Boolean
         }

         return YourParsedData.create(); //provide the functionality to take in the parsed data
       }
     }

你可以用它:

Gson gson = new GsonBuilder()
    .registerTypeAdapter(ServiceState.class, new ServiceDeserializer())
    .create();