1

I have json response ,where I have the array & objects with same name. I could not parse it with GSON. Is it impossible to parse that kind of json response with Gson? or, there is some way to parse the response with GSON?

Example of response:

 {
      "content": [
                   {
                     "type": "text",
                      "content": "adnan",
                      "class": "32",
                      "align": "1"
                   },
                   {
                     "type": "image",
                     "image": "http://adnanul.jpg",
                     "width": 590,
                     "content": "sarkar",
                     "height": 332,
                     "link": "http://hashtagfail.com/post/44606137082/mobile-services-android-serialization-gson",
                     "caption": "3",
                     "class": "332"
                   }
               ]
            }
Community
  • 1
  • 1

4 Answers4

1

The Error -

Exception is: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 26643 path $.data[1].content[27].content 

The problem is that, content field inside content field is a array not a String, that is not shown inside your code example, but it is what the exception means. It could be that in some cases content is a String and in some cases an array.

Here is a similar problem and a answer - Gson - Same field name, different types

Community
  • 1
  • 1
Mikelis Kaneps
  • 4,576
  • 2
  • 34
  • 48
0

Yes it is possible to archive this response.

    public class ContentEntity {

        private ArrayList<Content> content;

        public class Content {
            private String type;
            private String image;
            private int width;
            private int height;
            private String content;
            private String link;
            private String caption;
            @SerializedName("class")
            private String className;

// Add getter and setter here
        }
    }

try using below entity while parsing it using GSON.

Drup Desai
  • 912
  • 6
  • 18
0

Using default representation will propably cause this because you have keys with same name. Maybe writing an own deserializer will help.

Lets asume that you have a Java class name "Content" and the json-String represents an array of this object:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Content.class, new MyBrandNewContentDeserializer());

Gson gson = gsonBuilder.create();
Content[] conts = gson.fromJson(jsonInput, Content.class);

Within the deserializer you can react on the String type "content"

Otis Ottington
  • 425
  • 5
  • 17
0

Try using http://www.jsonschema2pojo.org/ . Just provide your json , select JSON as source type and then select Gson as annotation style. It will generate a POJO class

Smit Davda
  • 638
  • 5
  • 15