Json.NET deserializing contents of a JObject? - c#

If I have a JObject, which contains the property "Fields".
How do I pull out the contents of this property to an object[] with deserialized elements?
It seems like no matter what I do, I only get arrays of other JObjects.
myJObject["Fields"] {
"$type": "System.Object[], mscorlib",
"$values": [
123,
"hello"
]
}
In this case, I want to get an object array containing a long 123 and the string "hello".

Use ToObject():
var array = myJObject["Fields"].ToObject<object[]>();
Debug.Assert(array[0].Equals(123L)); // No assert
Debug.Assert(array[1].Equals("hello")); // No assert

Related

How to convert List of string(which are already in individual json data) into a single array of json result in c#?

So i have a List of string which holds Indivdual json data, because it is in c# .netCore it already holds escape character('\') for double quotes, but in real it displays correct value that i know, but next i want an array of all these individual json result as a whole json result. what i am doing is directly Serializing this list of string as shown in below code, but it is adding extra escape charaters. is there any other better way of doing this using JsonResult or something?
string json = JsonConvert.SerializeObject(ListOfIndiviualJson);
If I understood correctly, ListOfIndiviualJson is a List<string> that contains strings like
{
"key1": "value",
...
}
And you want to serialise it into something like:
[
{
"key1": "value",
...
},
...
]
You can Parse each of the JSON strings into JObject, then serialise the List<JObject>:
JsonConvert.SerializeObject(ListOfIndiviualJson.Select(JObject.Parse).ToList());
Obviously, if ListOfIndiviualJson actually contains JSON arrays instead of JSON objects, use JArray.Parse.
If I understood you correctly you have a list of json object stored as I string, but now you want it as an array of strings.
string json = #"
[
{ ""test1"" : ""desc1"" },
{ ""test2"" : ""desc2"" },
{ ""test3"" : ""desc3"" }
]";
JArray a = JArray.Parse(json);
var _len = a.Count; // will be 3
Then you can convert it to a string and in json view you will see normal output.

How to read jagged array

Am calling an API which returns the following array in a string format:
[
[
"9200bc80bff0432081d01d103940ffb0",
"HelloEarth",
"https://www.google.com",
"invalid domain",
"",
""
],
[
"6f269d6627624d61836d1d60b268ff6b",
"HelloPluto",
"yahoo",
"72f988bf86f141af91ab2d7cd011db47",
"11/30/2015 12:00:00 AM",
""
],
[
"6f269d6627624d61836d1d60b268ff6b",
"HelloMars",
"bing",
"APIClient",
"11/30/2015 12:00:00 AM",
""
]
]
My question is how to convert this string to Array? And If i want to read only the first element of first array, how to do it? i have attached only simplified string which actually contains more than than 3 arrays. but each array contains only six elements.
I don't know if it was intentional, but that "string format" is valid JSON.
You can use JSON.Net to deserialize it.
var data = "[[\"9200bc80bff0432081d01d103940ffb0\", \"HelloEarth\", \"https://www.google.com\", \"invalid domain\", \"\", \"\"],[\"6f269d6627624d61836d1d60b268ff6b\", \"HelloPluto\", \"yahoo\", \"72f988bf86f141af91ab2d7cd011db47\", \"11/30/2015 12:00:00 AM\", \"\"],[\"6f269d6627624d61836d1d60b268ff6b\", \"HelloMars\", \"bing\", \"APIClient\", \"11/30/2015 12:00:00 AM\", \"\"]]";
var array = Newtonsoft.Json.JsonConvert.DeserializeObject<string[][]>(data);
Console.WriteLine(array[0][0]);
Output: 9200bc80bff0432081d01d103940ffb0
https://dotnetfiddle.net/DXi041
You should use Json deserializer to convert your string to an a jagged array.
The you can access to your array as a regular array just taking in count that every position that it returns contains an array, and if you want to access to a specific position you need an index again.
var a = jagged[firstIndex]; //returns an array
var obj = a[secondIndex]; //get the object inside the array

Json returned with space

I'm trying to check if In the json there is a certain property. Actually I can do it in the following way:
var container = (JContainer)JsonConvert.DeserializeObject(responseText);
var x = container.ToString(Formatting.None);
var message = container["text"];
now the variable responseText is returned as:
{[
{
"trace": {
"details": {
"data": "[29-02-2016 17:37:32.931751]",
"type": "[info]",
"text": "[Done.]"
},
"context": {
"context": [
[
{
"ID": "John Dillinger"
}
]
]
}
}
}
]}
in the x variable I have removed the space and the final result is:
"[{\"trace\":{\"details\":{\"data\":\"[29-02-2016 17:37:32.931751]\",\"type\":\"[info]\",\"text\":\"[Done.]\"},\"context\":{\"context\":[[{\"ID\":\"John Dillinger\"}]]}}}]"
Now if the key isn't found I get null:
if (message == null)
{
return responseText;
}
the problem is that I perform the condition on the message variable that check if in the container (not formatted) there is the property, the problem is that I get this exception:
{"Accessed JArray values with invalid key value: \"text\". Int32 array index expected."}
but if I replace container with the second json with the slash all working good. Now my problem is that I can't execute var message= x["text"]; 'cause x is a string. So how I can remove the space in the json and check if contain the text key?
It looks like when you removed the space, you also changed the order of the first brackets In the first example your first brackets are {[, in the second they are [{
In json, the ordering makes a difference. {} means object and [] means array.
[{"data":"value"}] is legal because you are saying that you have an array of an object. {["value"]} is not legal because your object does not have a name for the array. The legal version would be { "data":["value"] }
Here is a handy web tool to verify your JSON syntax

Deserializing JSON with Json.NET fails if internal string array exists

I am using Json.NET 6.x and I noticed weird behaviour:
If I want to deserialize this simple JSON, I get an error:
The code to deserialize:
object o = Newtonsoft.Json.JsonConvert.DeserializeObject(text);
and the JSON:
[
{
"Username": "tb386",
"TimestampUpdated": "2015-01-19T18:49:52.771571+01:00",
"AuthTokens": [
"Ua7JR5E7hSAxjafp6dpMrvw3HlICW3ZZdDuArMaU5ks="
]
}
]
The error I get is:
Unexpected character encountered while parsing value: U. Path '', line 0, position 0.
If I remove the array, it works fine. But all I have to do, is to remove the string inside the array, making it empty:
[
{
"Username": "tb386",
"TimestampUpdated": "2015-01-19T18:49:52.771571+01:00",
"AuthTokens": [ ]
}
]
and then it works fine. I should also note that the serialized JSON was produced by the Newtonsoft library, so the source is the same library!
If I try a validator (like http://jsonlint.com/) on the JSON with the array, it valides OK!
Can anyone help me out here?
Additional information: Even if I add a string inside VS and write the JSON hardcoded, it fails!
string text = "[ {\"Username\": \"tb386\",\"TimestampUpdated\": \"2015-01-19T18:49:52.771571+01:00\",\"AuthTokens\": [\"Ua7JR5E7hSAxjafp6dpMrvw3HlICW3ZZdDuArMaU5ks=\"] } ]";
object o = Newtonsoft.Json.JsonConvert.DeserializeObject(text);
Version info on Newtonsoft dll:

Unable to Parse this Json string in c#

I tried using Newtonsoft.Json to deserialize this json string, but I'm not getting the desired output.
my json string is
[
{
"id": 1,
"key": "Residential Homeowner",
"i18nText": "unknown message code DB_ENUM_UserType_residentialhomeowner",
"i18nKey": "DB_ENUM_UserType_residentialhomeowner"
},
{
"id": 8,
"key": "VAR Dealer \/ Builder",
"i18nText": "unknown message code DB_ENUM_UserType_vardealer\/builder",
"i18nKey": "DB_ENUM_UserType_vardealer\/builder"
},
{
"id": 2,
"key": "Administrator",
"i18nText": "unknown message code DB_ENUM_UserType_administrator",
"i18nKey": "DB_ENUM_UserType_administrator"
},
{
"id": 9998,
"key": "TempGuidUser",
"i18nText": "unknown message code DB_ENUM_UserType_tempguiduser",
"i18nKey": "DB_ENUM_UserType_tempguiduser"
},
{
"id": 9999,
"key": "GuidUser",
"i18nText": "unknown message code DB_ENUM_UserType_guiduser",
"i18nKey": "DB_ENUM_UserType_guiduser"
}
]
I just want the value of key when value of id=1. Generally json starts with {}(curly bracket) but here it is like [](square bracket). I've seen many examples but none worked for me.
Generally json starts with {} (curly bracket), but here it is like [] (square bracket).
This is because you got an array of objects, not a single object. Arrays are serialized with square brackets around them. You should deserialize it into an array, and then grab the object at the index of interest.
This is a related post that addresses JSON parsing in C#: C# JSON Parsing.
If the brackets are a problem, simply use:
string json = inputJson.Trim().Trim('[',']');
If the id can have a minimum value of 1, then this should work:
string GetKey(string inputJson)
{
string key = inputJson.Substring(inputJson.IndexOf("key")+5);
key = key.Substring(key.IndexOf("\""), key.IndexOf(",")-key.IndexOf("\""));
key = key.Trim('\"');
return key;
}
If you are only interested in a single value from that larger JSON value, you may want to try Linq to JSON which would allow you to query over the JSON without deserializing everything.
Example:
JArray values = JArray.Parse(json);
string key;
var keyObject = values.FirstOrDefault(p => (int)p["id"] == 1);
if (keyObject != null)
{
key = (string)keyObject["key"];
}
[] is to define a json object array. Your output should be an array. Traverse through the array like:
for(var i=0; i<output.Length; i++)
{
if(output[i].id == "1") // desired id
{
Console.WriteLine(output[i].key);// use it as you wish
}
}
and use the found objects key.

Categories