C# Json deserialization error - c#

I want to convert json string to C# datatable and my json string contains another json string.
I don't want to convert internal json string (keep it as string only). this is my code
string js = "[{\"FirstName\":\"first\",\"LastName\":\"second\",\"jsonStr\":\"[{\"abc\":\"a\",\"xyz\":\"x\"}]\"}]";
DataTable dt = (DataTable)JsonConvert.DeserializeObject(js, (typeof(DataTable)));
gv.DataSource = dt;
gv.DataBind();
But I am getting an error
After parsing a value an unexpected character was encountered: a. Path
'[0].jsonStr', line 1, position 56.

Your JSON is invalid. After unescaping, it becomes the following string:
[
{
"FirstName" : "first",
"LastName" : "second",
"jsonStr" : "[{" abc ":" a "," xyz ":" x "}]"
}
]
Stack Overflow syntax highlighting suggests that your JSON is invalid.
You can also check the JSON validity here.
In order to make it valid, your quotes within jsonStr should have been escaped again:
string js = "[{\"FirstName\":\"first\",\"LastName\":\"second\",\"jsonStr\":\"[{\\\"abc\\\":\\\"a\\\",\\\"xyz\\\":\\\"x\\\"}]\"}]";
This C# string now contains the following JSON, which is valid:
[
{
"FirstName": "first",
"LastName": "second",
"jsonStr": "[{\"abc\":\"a\",\"xyz\":\"x\"}]"
}
]

Related

When deserializing Json string that contains "\" gives Bad Json escape sequence

I have a input field in UI which contains a field Value with "\\test\a\b\c". The Json string in API after serialization has the Value field as below.
{
"ItemKey": "8b603493-3d2d-4903-a054-2abb895ab870",
"ParentKey": "00000000-0000-0000-0000-000000000000",
"Schema": "",
"SchemaTypeName": "",
"Value": "\\\\test\\a\\b\\c",
"ValueDefinition": null
}
When deserializing this string I get the error,
var result = JsonConvert.DeserializeObject<Class>(rootElement);
{"Bad JSON escape sequence: \\M. Path 'sample[0].sample[1].Value', line 1, position 3384."}
I tried double escaping "\" and this error is resolved.
var tempStr = valueReplacement.Replace(#"\\", #"\").Replace(#"//", #"/");
valueReplacement = tempStr.Replace(#"\", #"\\").Replace(#"/", #"//");
{"Value": "\\test\\a\\b\\c"}
But I need the final json that is generated after deserializing to have the value still the same because I need to integrate this with UI.
"Value": "\\test\a\b\c"
Is there any way I can change the value again after deserialization?

Dynamic JObject - parse invalid JSON

Consider I have following json:
{ "version": "1.0" }
I can parse it to dynamic JObject and use:
dynamic result = JObject.Parse(myJson);
string verison = result.Version; //works <3
But server returns the following json
{ { "version": "1.0" } }
This json is consider as valid by newtonsoft, but cannot access version anymore:
dynamic result = JObject.Parse(myJson);
string verison = result.Version; //error
How to access Version when onlt dynamic result is avalable?
{ { "version": "1.0" } } This json is consider as valid by newtonsoft
That is incorrect, you will not be able to parse this and will receive a exception of type Newtonsoft.Json.JsonReaderException (with: Invalid property identifier character: {. Path '', line 1, position 2.)
Invalid JSON:
{ { "version": "1.0" } }
Valid JSON:
{ "version": "1.0" }
(In case you have server control, I suggest you make the necessary steps on the server to return valid JSON)
However, worst case scenario, you could make this invalid JSON valid by removing the first char { and last char } before parsing it. For example like so:
var myJson = json.Substring(1, json.Length - 2);
dynamic result = JObject.Parse(myJson);
string version = result.version;
Where json here was the original response containing the invalid JSON.
Also note that for the JSON you provided you must use lowercase version as result.version. The dynamic property name must match exactly the one in the JSON
I think you trouble in capital "V" in "Version". Should be "result.version"

How to convert JSON string with different value types to C# Dictionary?

So, I want to convert this JSON string:
{
"Posts" :
[
{
"Title" : "just a string",
"Id" : "231"
}, {
"Title" : "Another string as title",
"Id": "41"
}
],
"anotherKey" : "third string"
}
to C# Dictionary, but this code (using Newtonsoft.Json package; where jsonString is variable storing that JSON string):
Dictionary<string,Array> test1 = JsonConvert.DeserializeObject<Dictionary<string,Array>>(jsonString);
Console.WriteLine(test1.Count);
returns an error:
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
Additional information: Unable to find a constructor to use for type System.Array. Path 'Posts', line 1, position 10.
Is another way how to convert this string to Dictionary?
The second entry isn't an array, it's a single string.
Try deserializing to Dictionary<string,object> or Dictionary<string,dynamic> to read all values.

Extracting a JSON object from a serialized string in C#

Assuming I have a string that looks like this ...
string s = "{ \"id\": \"1\", \"name\" : \"Test\" } has other text in the same string";
Is there a way, in C#, to extract the JSON part of the text as its own "token" when splitting the string apart?
The goal is very simple. In a string that contains text, and possibly a JSON object, I just wanted to try and separate the text from the JSON so that I could pass one off to the appropriate facility. There is no deserialization needed, there is no validation needed, and there is no need to turn the JSON text into an object. I just wanted to be able to pull the text out.
When you are dealing with json, use a real json parser like Json.net. Regex is not enough to handle all extreme cases.
For example, suppose a string field which contains [ and you use Garath's answer. Booom.
string s = "{ \"id\": \"1\", \"name\" : \"Test\" }";
var anonymousObject = new { id = 0, name = "" };
anonymousObject = JsonConvert.DeserializeAnonymousType(s, anonymousObject);
Console.WriteLine(anonymousObject.name);
Other Serializer alternatives: JavaScriptSerializer, DataContractJsonSerializer .......
Bellow code should do what you are looking for (I tested it):
string s = "{ \"id\": \"1\", something:{xx:22, yyy: \"3\"}, \"name\" : \"Test\" } has other text in the same string";
var regexp = new Regex("([{].+[}])");
var match = regexp.Match(s);

Invalid Json Primitives

Could you help me for resolving this issue. I have one asp.net application, in this i am using Javascript serializer for serializing a dataset followed by convertion to the list. That code is shown below.
JavaScriptSerializer json = new JavaScriptSerializer();
strJson = json.Serialize(aclDoc);
But, at the time of deserializing i got one ArguementException like Invalid Json Primitives with my Json value. My json value is
[{"Id":"F79BA508-F208-4C37-9904-DBB1DEDE67DB","App_Id":"ScriptFlow","Name":"New form","FriendlyName":"","Read":"Revoke","ReadRule":"a353776f-cbdc-48b7-a15b-4a2316d19b05","Update":"Grant","UpdateRule":"be30c34e-33ec-4c0a-9f09-4fd483f5f1b9","Create":"Revoke","CreateRule":"898dce4d-4709-45b6-8942-d7efb07cbd86","Delete":"Revoke","DeleteRule":"aa14d435-dec8-4ade-ad9b-830ae5ee15d0"}][{"Id":"1","Doc_Id":"858E013C-5775-4FDF-AA1E-2C84053EE39F","Name":"TextBox1","FriendlyName":"TextBox1","Read":"Grant","ReadRule":"0a2e3c0e-ad8f-4f75-9160-cfd9827ac894","Update":"Grant","UpdateRule":"ecad3cf4-104f-44dc-b815-de039f3a0396"},{"Id":"2","Doc_Id":"858E013C-5775-4FDF-AA1E-2C84053EE39F","Name":"TextBox2","FriendlyName":"TextBox2","Read":"Grant","ReadRule":"81e0e9ef-09f7-4c25-a58e-d5fdfbd4c2ba","Update":"Grant","UpdateRule":"2047f662-c881-413b-a1f9-69f15bf667fc"}]
The code for deserializing is:
JavaScriptSerializer json = new JavaScriptSerializer();
lstDoc = json.Deserialize<List<ACLDocument>>(value);
return lstDoc;
where lstDoc is a List Collection of type of my class
I got the exception like this:
Invalid JSON primitive:
{"Id":"1","Doc_Id":"858E013C-5775-4FDF-AA1E-2C84053EE39F","Name":"TextBox1","FriendlyName":"TextBox1","Read":"Grant","ReadRule":"0a2e3c0e-ad8f-4f75-9160-cfd9827ac894","Update":"Grant","UpdateRule":"ecad3cf4-104f-44dc-b815-de039f3a0396"},{"Id":"2","Doc_Id":"858E013C-5775-4FDF-AA1E-2C84053EE39F","Name":"TextBox2","FriendlyName":"TextBox2","Read":"Grant","ReadRule":"81e0e9ef-09f7-4c25-a58e-d5fdfbd4c2ba","Update":"Grant","UpdateRule":"2047f662-c881-413b-a1f9-69f15bf667fc"}].
Please help me for resolving this issue. Thanks in advance
Your input string is really a wrong JSON string. You input consist from two correct JSON strings:
[
{
"Id": "F79BA508-F208-4C37-9904-DBB1DEDE67DB",
"App_Id": "ScriptFlow",
"Name": "New form",
"FriendlyName": "",
"Read": "Revoke",
"ReadRule": "a353776f-cbdc-48b7-a15b-4a2316d19b05",
"Update": "Grant",
"UpdateRule": "be30c34e-33ec-4c0a-9f09-4fd483f5f1b9",
"Create": "Revoke",
"CreateRule": "898dce4d-4709-45b6-8942-d7efb07cbd86",
"Delete": "Revoke",
"DeleteRule": "aa14d435-dec8-4ade-ad9b-830ae5ee15d0"
}
]
and
[
{
"Id": "1",
"Doc_Id": "858E013C-5775-4FDF-AA1E-2C84053EE39F",
"Name": "TextBox1",
"FriendlyName": "TextBox1",
"Read": "Grant",
"ReadRule": "0a2e3c0e-ad8f-4f75-9160-cfd9827ac894",
"Update": "Grant",
"UpdateRule": "ecad3cf4-104f-44dc-b815-de039f3a0396"
},
{
"Id": "2",
"Doc_Id": "858E013C-5775-4FDF-AA1E-2C84053EE39F",
"Name": "TextBox2",
"FriendlyName": "TextBox2",
"Read": "Grant",
"ReadRule": "81e0e9ef-09f7-4c25-a58e-d5fdfbd4c2ba",
"Update": "Grant",
"UpdateRule": "2047f662-c881-413b-a1f9-69f15bf667fc"
}
]
but you can not concatenate two JSON strings. To say exactly what you receive after such concatenating in not more a JSON string.
I recommend you to verify JSON strings in http://www.jsonlint.com/. Just cut and paste the data which you need to verify and click "Validate" button.
To answer the question directly, since everyone thinks this is a Microsoft forum and not answering directly.
The string is sent as a 2 element array. You forgot the '[' in the beginning of the string which denotes that the containing values are an array structure.
Insert the '[' in the beginning of the string and the error should go away.
This is a useful little tool for examining your JSON objects:
http://jsonviewer.codeplex.com/
See if you have any // or commented lines in project.json
Removing this has solved the same problem for me

Categories

Resources