如何使用gson处理动态响应数据? (json到java对象)

时间:2013-10-01 19:34:35

标签: java json

以下是Json用户列表:

{
    'response': {
        'result': {
            'users': [{
                name: "ABC",
                age: "20",
                gender: "F"
            },
            {
                name: "cbd",
                age: "23",
                gender: "M"
            }]
        }
    }
}

有时会像这样回归

{
    'response': {
        'result': {
            'users': {
                name: "ABC",
                age: "20",
                gender: "F"
            }
        }
    }
}

当返回单个用户时,我可以使用以下java类将json转换为java

class Data{
    private response response;
    class response{
        private result result;
        class result{
            private users users;
            class users{
                private String name;
                private String age;
                private String gender;

            }

        }
    }

}

但是如果返回用户列表,我会得到Exception。我怎么处理呢?

1 个答案:

答案 0 :(得分:1)

要执行您想要的操作,您必须将users更改为List<User> 编写(简单)自定义反序列化程序。如果没有自定义反序列化器,Gson将无法解析,除非您将用户切换到Object(但在这种情况下,它将返回一个映射列表)。

在向您展示可以在IDE中复制和运行的完整示例之前,请注意两个注意事项。用户“而不是”作为字符串分隔符,遵循Java命名约定。类必须至少以大写字母开头。放置小写不会改变Gson行为,因为它查看类字段< / em>名称不是类名。

package stackoverflow.questions.q19124387;

import java.lang.reflect.Type;
import java.util.*;



import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

public class Q19124387 {

   public static class User {
      private String name;
      private String age;
      private String gender;
      @Override
      public String toString() {
         return "User [name=" + name + ", age=" + age + ", gender=" + gender + "]";
      }



   }

   public static class Result {
      private List<User> users = new ArrayList<User>();

   }

   public static class Response {
      private Result result;

   }

   public static class Data {
      private Response response;

   }

   public static class CustomDeserializer implements JsonDeserializer<Result> {

      public Result deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

         Result r = null;

         JsonElement usersField = json.getAsJsonObject().get("users");
         if (usersField.isJsonNull() || usersField.isJsonPrimitive())
            ; // if is null or is a primitive type will return an empty result
         else if (usersField.isJsonObject()) {
            r = new Result();
            r.users.add((User) context.deserialize(usersField, User.class));

         } else if (usersField.isJsonArray()) {
            Type listOfUserType = new TypeToken<List<User>>() {}.getType();
            r = new Result();

            r.users.addAll((Collection<? extends User>) context.deserialize(usersField, listOfUserType));

         }
         return r;

      }

   }

   /**
    * @param args
    */
   public static void main(String[] args) {
      String json1 = " {\"response\": {  \"result\": { \"users\": [{ name: \"ABC\",  age: \"20\", gender: \"F\"  },  { name: \"cbd\",  age: \"23\", gender: \"M\"  }] }  }  }";

      String json2 = "{\"response\": { \"result\": {\"users\": { name: \"ABC\", age: \"20\",gender: \"F\" } } } }  ";

      Gson g = new Gson();
      try {
         Data d1 = g.fromJson(json1, Data.class);
         System.out.println("Parsed json1, list of users");
      } catch (Exception e) {
         System.out.println("Cannot parse json1, list of users");
      }
      try {
         Data d2 = g.fromJson(json2, Data.class);
         System.out.println("Parsed json2, single user");
      } catch (Exception e) {
         System.out.println("Cannot parse json2, single user");
      }

      GsonBuilder gb = new GsonBuilder();
      gb.registerTypeAdapter(Result.class, new CustomDeserializer());
      Gson g2 = gb.create();

      Data d1 = g2.fromJson(json1, Data.class);
      Data d2 = g2.fromJson(json2, Data.class);

      System.out.println("Second user of json1 is " + d1.response.result.users.get(1));
      System.out.println("First user of json2 is " + d2.response.result.users.get(0));

   }

}

这是代码的执行:

Parsed json1, list of user
Cannot parse json2, single user
Second user of json1 is User [name=cbd, age=23, gender=M]
First user of json2 is User [name=ABC, age=20, gender=F]