0

I have a json string in this format :

 [
   {
     "key1": { "key1":"val1","key2":"val2" },
     "key2": { "key1":"val1","key2":"val2" }
   }
]   

To parse it I created a java class :

class data {
     String key;
     List <content> listdata;
     /* getter and setter for the attribute above */
     ...
   } 

Now I followed Gson documentation, and try to exract data :

Gson gson =new Gson();
data[] ints = gson.fromJson(MyjsonString, data[].class); 

I get parsing error from Gson API, what I done wrong ?

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path
2
  • Are you sure, your data should not look like this? [ { "key": [ "key1":"val1","key2":"val2" ]}, { "key": [ "key1":"val1","key2":"val2" ]}] Commented Dec 22, 2015 at 12:07
  • No its like what i presented above Commented Dec 22, 2015 at 12:14

2 Answers 2

1

For parsing json like following class

class data {
String key;
List <content> listdata;
/* getter and setter for the attribute above */
...
} 

you need a json like as follows

"data" : {
 "key": "value",
 "listdata": [{ content object key attributes here }]
}

As your exception clearly saying BEGIN_ARRAY but was STRING so you have to use array in json for parsing.

In Reply of your comment

If you want a class which parse following json

{
 "key1": { "key1":"val1","key2":"val2" },
 "key2": { "key1":"val1","key2":"val2" }
}

Then you would have classes structure as follows

class Data {
 Map<String, String> key1;
 Map<String, String> key2;
 /* getter and setter for the attribute above */
} 
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for the answer, i know that i have to change my class structure but, can you suggest me a new one ?
I can't so change my Json String, but i can change my java class to suite the requirement.
You have changed the message structure with this { key:{ content }, key2: {conetent }}, but how we can do it without omit [], i mean to save the message like this [{{},{}}] ?
well, then you can use Map<String, String> key1 and Map<String, String> key2 in Data class this is very easy to use. also see my updated answer!
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path
0

As per the Json, this class structure works:

class data {
 List <Map<String,Content> data;
 /* getter and setter for the attribute above */
 ...

}

3 Comments

com.google.gson.stream.MalformedJsonException: Expected ':' at line 1 column 9 path
something is wrong with the json, check your json, you could use jsonlint.com
i tested it in this link its a valid json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.