Neetesh
Neetesh

Reputation: 917

Reading Json String using Gson results error "not a JSON Array"

In my project i have a complex json response. I want to read it by GSon.

JSON : {'FoodMenuRS':{'Results':[{'Items':{'Item':[{'@Id':'24'},{'@Id':'24'}]}}, {'Items':{'Item':{'@Id':'24'}}}]}}

It contains a JSONArray with first "Item" and JSONObject with second one. Hence its call results in error,

failed to deserialize json object {"@Id":"24"} given the type java.util.List<com.servlet.action.ItemInfo>  and  java.lang.IllegalStateException: This is not a JSON Array.

Please help how i should handle this scenario. Thanks.

Upvotes: 4

Views: 5108

Answers (3)

Gabriel Llamas
Gabriel Llamas

Reputation: 18427

Your JSON is valid, but not for the doble quotes (") because JSON supports simple quotes (') and no quotes in the key name. See http://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Colle

However this JSON have key names that begin with @. For JSON strings this character is valid at the beginning of the name (see right column http://www.json.org/) but for Java this names are illegal (see Naming section http://download.oracle.com/javase/tutorial/java/nutsandbolts/variables.html). Specifically, names started with @ are annotations and you can't use annotations tags to declare variables, fields, methods, etc.

Upvotes: 0

Lalit Poptani
Lalit Poptani

Reputation: 67286

The string you are showing is a JSONObject not a JSONArray. So, in this case you first of all have to get the JSONObject and perform further decoding on that JSONObject.

JSONObject - {}

JSONArray - []

And indeed JSONObject or JSONArray should be encoded using Double-quotes(")

Upvotes: 6

phihag
phihag

Reputation: 287795

This is not a valid JSON object. Strings in JSON are always encapsulated in double quotes ("). Contact the producer of that JSON and tell him to use a correct encoder.

Upvotes: -1

Related Questions