alle3x
alle3x

Reputation: 495

Parsing JSON Array to Java List Using Gson

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"
     ]
}

Upvotes: 1

Views: 675

Answers (2)

Michał Ziober
Michał Ziober

Reputation: 38645

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'}

Upvotes: 2

RAJKUMAR NAGARETHINAM
RAJKUMAR NAGARETHINAM

Reputation: 1518

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);

    }
}

Upvotes: 0

Related Questions