更新时间:2023-01-17 12:00:31
如果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'}