Here is Json list of users:
这里是Json用户列表:
{
'response': {
'result': {
'users': [{
name: "ABC",
age: "20",
gender: "F"
},
{
name: "cbd",
age: "23",
gender: "M"
}]
}
}
}
And sometimes return like this
有时像这样回来
{
'response': {
'result': {
'users': {
name: "ABC",
age: "20",
gender: "F"
}
}
}
}
When it is return single user I can use following java class to covert json to java
当它返回单个用户时,我可以使用以下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;
}
}
}
}
but if returns lists of users I get Exception. How can I handle it?
但是如果返回用户列表,我就会得到异常。我怎么处理呢?
1 个解决方案
#1
1
To do what you want, you have to change users
to a List<User>
and write a (simple) custom deserializer. Without custom deserializer Gson won't parse, unless you switch users to Object
(but in that case it will return a list of maps).
要实现您想要的功能,您必须将用户更改为一个列表
Before showing you a full example that you can copy and run in your IDE, two notes. User " instead of ' as string delimiter and follow Java naming conventions. Classes must have at least first letter in upper case. Putting lowercase won't change Gson behavior since it looks at class fields name not to class names.
在向您展示可以在IDE中复制和运行的完整示例之前,有两个注意事项。用User而不是' as string delimiter并遵循Java命名约定。类必须至少有大写字母。使用小写不会改变Gson行为,因为它查看类字段名而不是类名。
package *.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));
}
}
this is the execution of code:
这是代码的执行:
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]
#1
1
To do what you want, you have to change users
to a List<User>
and write a (simple) custom deserializer. Without custom deserializer Gson won't parse, unless you switch users to Object
(but in that case it will return a list of maps).
要实现您想要的功能,您必须将用户更改为一个列表
Before showing you a full example that you can copy and run in your IDE, two notes. User " instead of ' as string delimiter and follow Java naming conventions. Classes must have at least first letter in upper case. Putting lowercase won't change Gson behavior since it looks at class fields name not to class names.
在向您展示可以在IDE中复制和运行的完整示例之前,有两个注意事项。用User而不是' as string delimiter并遵循Java命名约定。类必须至少有大写字母。使用小写不会改变Gson行为,因为它查看类字段名而不是类名。
package *.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));
}
}
this is the execution of code:
这是代码的执行:
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]