JSON string parsing issue in C# - c#

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?

Related

C# Pass filename as json parameter- Getting error "Unrecognized escape sequence. "

I want to pass a filepath through JSON. On deserializing I am getting error:
Unrecognized escape sequence. (43): {"Jobtype": "StepBatch","SelectedId": "D:\Input\file1.CATPart"}
I have escaped characters but it still shows error...am I missing something here?
string json = "{\"Jobtype\": \"StepBatch\",\"SelectedId\": \"D:\\Input\\file1.CATPart\"}";
var jsonObj = new JavaScriptSerializer().Deserialize<List<Arguments>>(json);
The problem is that the content of your string at execution time is:
{"Jobtype": "StepBatch","SelectedId": "D:\Input\file1.CATPart"}
That's not valid JSON, because of the backslashes in the value for SelectedId. You'd need the JSON to be:
{"Jobtype": "StepBatch","SelectedId": "D:\\Input\\file1.CATPart"}
so your C# would have to be:
string json = "{\"Jobtype\": \"StepBatch\",\"SelectedId\": \"D:\\\\Input\\\\file1.CATPart\"}";
However, given that you're immediately deserializing the JSON anyway, I'd suggest getting rid of the JSON part entirely, and just creating the Arguments values yourself.
If you need to produce JSON, create the right values directly, and then get JavaScriptSerializer (or preferrably Json.NET) to create the JSON for you, instead of hand-coding it.

How to Convert a string containing escaped JSON to object?

I have a JSON received from a third part, which I can't change.
This JSON has a property with special characters
"CryptoKey":"dqwe`fqer]OS#xMKA^Qd[3123ddFjqr412_hRHBXTfNEyp\lVLoia",
So, when I try to deserialize it, I receive the following error:
Newtonsoft.Json.JsonReaderException: 'Bad JSON escape sequence: \l. Path '['148/FOEConfiguration'].CryptoKey', line 7, position 75.'
What I'm doing is:
string text = File.ReadAllText(configFile);
dynamic result = JsonConvert.DeserializeObject(text);
Is there a way to deserialize this to an object without breaking it?
Or I'll have to read in a diferent way?

Can I Deserialize a JSON string that contains 0.0 in C#?

The JSON I'm getting back from a webservice has an integer incorrectly represented as 0.0. My deserialization code looks like this:
var serializer = new JsonSerializer();
var ret = serializer.Deserialize<T>(jsonTextReader);
And I get an error like this:
Input string '0.0' is not a valid integer.
My question is, is there a way to specify a less strict deserialization method so that I can parse this string?
EDIT: The web service returns no schema so I don't know why the deserializer tries to convert it to an int instead of a float or double.
I'd say that you should go ahead and creat your classes on Json -> C#
var o = (JObject)serializer.Deserialize(myjsondata);
You can use the C# dynamic type to make things easier. This technique also makes re-factoring simpler as it does not rely on magic-strings. Use JsonConvert.DeserializeObject<dynamic>()to deserialize this string into a dynamic type then simply access its properties in the usual way in C#.
Im not sure why youre getting
Input string '0.0' is not a valid integer.
since if you dont have any Json data it should just be left at null and you shouldnt have this problem

Send JSON snippet as string as part of larger JSON request

I'm interacting with a Web API in which all communication is done with JSON - i.e. we serialise data to send them to them and vice versa.
This works fine, but there is a field called 'CustomData' which is a string type, and we want to use this to store 2-3 more variables. The API requires to send through a JSON string which it then stores and parses internally. However, this JSON is obviously being deserialised on their end as an object and we're getting an error saying it's expecting a string but has got an object.
Is there anyway I can mark this string field as raw JSON, and instruct the server NOT to deserialise it?
I'm using JSON.NET
May be try to encode the JSON string from the sender's side and decode it on your receiving end before adding to your database? That way your overall JSON deserialize won't recognize the data string as JSON.

JavaScriptSerializer value for i=3?

JavaScriptSerializer oSerializer = new JavaScriptSerializer();
object i = 3;
string sJSON = oSerializer.Serialize(i); //"3"
The JavaScriptSerializer should serialize its parameter to JSON!
And the result is "3" ( which is not JSON)
What am I missing?
edit
Ive written a mail to douglas crockford
3 is not a json object/text but json value.
so i think msdn should clarify the serialize method.
http://i.stack.imgur.com/VOh3X.png
As has been said many times by different people, the output you are receiving is valid JSON.
From the JSON Specification (the Introduction):
JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).
and further (Section 2.1):
A JSON value MUST be an object, array, number, or string, or one of the following three literal names:
false null true
My interpretation of specification tells me that the case you describe here is more a JSON value than a JSON object.
You asked it to serialise the value 3, and it did. That's exactly correct.
To be explicit: what exactly are you expecting to come out? JSON gives name-value pairs. The value "3" has no name, because the whole object is 3.
JSON is JavaScript object notation. Pass it an object, and you'll probably get what you're expecting.
You can use an anonymous type as M. Babcock suggests: new { i = 3 }.

Categories