使用Gson将JSON数组解析为Java列表 [英] Parsing JSON Array to Java List Using Gson
问题描述
从给定的JSON
生成SimpleTestClass
类型的List
的最佳方法是什么,其中JSON
中recipients
数组中的值有一个新的SimpleTestClass
对象,代码设置为出色地.
What is the best way from the given JSON
to generate List
of SimpleTestClass
type where there's a new SimpleTestClass
object for the values in the recipients
array in the JSON
with code set as well.
public class SimpleTestClass{
String code;
String recipient;
}
JSON
有效载荷:
{
"code": 123,
"recipients": [
"888888",
"222222"
]
}
推荐答案
如果JSON
结构不适合POJO
模型,则需要编写自定义反序列化器或创建适合JSON
的新POJO
模型,经过反序列化过程后,将其转换为所需的模型.在下面,您可以找到带有自定义反序列化器的解决方案,该解决方案使您可以非常灵活地处理给定的JSON
:
If JSON
structure does not fit to POJO
model you need to write custom deserialiser or create a new POJO
model which fits JSON
and after deserialisation process convert it to required model. Below you can find solution with custom deserialiser which allow you to handle given JSON
in a very flexible way:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.JsonAdapter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class GsonApp {
public static void main(String[] args) {
String json = "{\"code\": 123,\"recipients\": [\"888888\",\"222222\"]}";
Gson gson = new GsonBuilder().create();
List<Recipient> recipients = gson.fromJson(json, Recipients.class).getRecipients();
recipients.forEach(System.out::println);
}
}
class RecipientsJsonDeserializer implements JsonDeserializer<Recipients> {
@Override
public Recipients deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
List<Recipient> recipients = new ArrayList<>();
JsonObject root = json.getAsJsonObject();
String code = root.get("code").getAsString();
JsonArray recipientsArray = root.getAsJsonArray("recipients");
recipientsArray.forEach(item -> {
recipients.add(new Recipient(code, item.getAsString()));
});
return new Recipients(recipients);
}
}
@JsonAdapter(RecipientsJsonDeserializer.class)
class Recipients {
private final List<Recipient> recipients;
public Recipients(List<Recipient> recipients) {
this.recipients = recipients;
}
// getters, toString
}
class Recipient {
private final String code;
private final String recipient;
public Recipient(String code, String recipient) {
this.code = code;
this.recipient = recipient;
}
// getters, toString
}
上面的代码显示:
Recipient{code='123', recipient='888888'}
Recipient{code='123', recipient='222222'}
这篇关于使用Gson将JSON数组解析为Java列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!