Parsing JSON Array to Java List Using Gson

好久不见. 提交于 2019-12-13 03:58:25

问题


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 payload:

{
     "code": 123,
     "recipients": [
        "888888",
        "222222"
     ]
}

回答1:


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
}

Above code prints:

Recipient{code='123', recipient='888888'}
Recipient{code='123', recipient='222222'}



回答2:


class SimpleTestClass {
    String code;
    List<String> recipients;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public List<String> getRecipients() {
        return recipients;
    }

    public void setRecipients(List<String> recipients) {
        this.recipients = recipients;
    }

}

public class ServerMain {
    public static void main(String[] args) {

        Gson g = new Gson();
        SimpleTestClass class = g.fromJson(json, SimpleTestClass.class);

    }
}


来源:https://stackoverflow.com/questions/55688208/parsing-json-array-to-java-list-using-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!