0

The JSON string that I receive is inconsistent. Sometimes some of the data elements in the JSON return as 'List ' type, the other times return as 'dictionary' type. Currently using JavaScriptSerializer to Deserialize the JSON string, but it gives me an exception in the cases like

for example - I have a data field "jpjhseq" which I have declared as a dictionary but at times the JSON string returns this as a string and I get an exception. This issue happens for other fields as well.

JavaScriptSerializer serializer = new JavaScriptSerializer();

Foo foo = serializer.Deserialize<Foo>(jsonString);

Many a times I get following json string

{"element1":{"0":"0","1":"S","2":"S","3":"J","4":"Q","5":"X","6":"M"},"element2":{"1":"one" ,"2":"two","4":"four","5":"five","6":"six","7":"seven","8":"eight"}}

for other data i get following json string

{"element1":["0","S","S","J","Q","X","M"],"element2":["one" ,"two","four","five","six","seven","eight"]}

How can i write a generic json parser for such inconsistent json strings? Key names will be standard, but the data type of their values may vary.

What can be done to resolve this issue?

panda5
  • 9
  • 2
  • 4
    We will need to see the structure of `jsonString`. – Jamie Rees Feb 16 '16 at 09:02
  • 2
    JSON.NET can cope with inconsistency by defining custom parsers for certain fields. However, as Jamie R suggests, we need to see examples of your data to be able to help you further. But please comment if you are willing to use JSON.NET or if you want the solution to be with JavaScriptSerializer only. – Wapac Feb 16 '16 at 09:05
  • 1
    You could consider casting it to dictionary always and then figure out if it's actually a list. http://stackoverflow.com/a/1212115/390421 – MartijnK Feb 16 '16 at 09:07
  • 1
    I am open to use json.net. but if i get solution of javascriptserializer, i would use it first. – panda5 Feb 16 '16 at 09:12
  • If you have any control over the returns JSON, how would change it structure because JSON structure for a given ACTION should always be on the same structure. Action1 => JSON1 structure, Action2 => JSON2 structure, but the following should never happen: Action1 => JSON1 and sometimes also JSON2. If the latter is the case, how would make some function that will identify which of the json is being used(By RegularExpression or a simple IndexOf) and by the returns type i will activate the correct JsonDeserializer. – Orel Eraki Feb 16 '16 at 09:40

0 Answers0