Gson how to deserialize an array or empty string

I am trying to deserialize this json for an array of objects:

[{
    "name": "item 1",
    "tags": ["tag1"]
},
{
    "name": "item 2",
    "tags": ["tag1","tag2"]
},
{
    "name": "item 3",
    "tags": []
},
{
    "name": "item 4",
    "tags": ""
}]

My java class is as follows:

public class MyObject
{
    @Expose
    private String name;

    @Expose
    private List<String> tags = new ArrayList<String>();
}

The problem is the json tags property, which may just be an empty string or an array. Now gson gives me an error:com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING

How do I deserialize this json?

I have no control over this json, it comes from the third pary api.

+4
source share
6 answers

I have no control over this json, it comes from the third pary api.

If you do not have control over the data, the best solution is to create a custom deserializer, in my opinion:

class MyObjectDeserializer implements JsonDeserializer<MyObject> {
    @Override
    public MyObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jObj = json.getAsJsonObject();
        JsonElement jElement = jObj.get("tags");
        List<String> tags = Collections.emptyList();
        if(jElement.isJsonArray()) {
            tags = context.deserialize(jElement.getAsJsonArray(), new TypeToken<List<String>>(){}.getType());
        }
        //assuming there is an appropriate constructor
        return new MyObject(jObj.getAsJsonPrimitive("name").getAsString(), tags);
    }
}

What does he do to check whether "tags" JsonArrayor not. If so, he will deserialize it, as usual, otherwise you will not touch it and just create your object with an empty list.

, JSON:

Gson gson = new GsonBuilder().registerTypeAdapter(MyObject.class, new MyObjectDeserializer()).create();
//here json is a String that contains your input
List<MyObject> myObjects = gson.fromJson(json, new TypeToken<List<MyObject>>(){}.getType());

, :

MyObject{name='item 1', tags=[tag1]}
MyObject{name='item 2', tags=[tag1, tag2]}
MyObject{name='item 3', tags=[]}
MyObject{name='item 4', tags=[]}
+5

json , "tags": "" "tags": []

+1

. , .

"tags": ""

"tags": null

.

0

GSON fromJson() JSON.

, :

import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class JsonToJava {

/**
 * @param args
 */
public static void main(String[] args) {
    String json = "[{\"firstName\":\"John\", \"lastName\":\"Doe\", \"id\":[\"10\",\"20\",\"30\"]},"
            + "{\"firstName\":\"Anna\", \"lastName\":\"Smith\", \"id\":[\"40\",\"50\",\"60\"]},"
            + "{\"firstName\":\"Peter\", \"lastName\":\"Jones\", \"id\":[\"70\",\"80\",\"90\"]},"
            + "{\"firstName\":\"Ankur\", \"lastName\":\"Mahajan\", \"id\":[\"100\",\"200\",\"300\"]},"
            + "{\"firstName\":\"Abhishek\", \"lastName\":\"Mahajan\", \"id\":[\"400\",\"500\",\"600\"]}]";

    jsonToJava(json);
}

private static void jsonToJava(String json) {
    Gson gson = new Gson();
    JsonParser parser = new JsonParser();
    JsonArray jArray = parser.parse(json).getAsJsonArray();

    ArrayList<POJO> lcs = new ArrayList<POJO>();

    for (JsonElement obj : jArray) {
        POJO cse = gson.fromJson(obj, POJO.class);
        lcs.add(cse);
    }
    for (POJO pojo : lcs) {
        System.out.println(pojo.getFirstName() + ", " + pojo.getLastName()
                + ", " + pojo.getId());
    }
}

}

POJO:

public class POJO {

  private String        firstName;
  private String        lastName;
  private String[]  id;
  //Getters and Setters.

, .

0

Jackson type security is better than Gson. From time to time you will use stackoverflow in Gson.

-1
source

Source: https://habr.com/ru/post/1599081/


All Articles