Need help to deserialize JSON string in C# - c#

I have a JSON string as below.
{"checkbox-1026":"eba8786c-f31d-4c5a-92ce-2d8ffd7c1066","checkbox-1027":"1b529116-1c58-4ac5-ad9d-04bd0d296335"}
I need to get values "eba8786c-f31d-4c5a-92ce-2d8ffd7c1066" and "1b529116-1c58-4ac5-ad9d-04bd0d296335".
Can anyone help me to get the values?

Try with Newtonsoft.JSON. Sample below shows how to get those values
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(j1);
foreach (var kvp in dict)
{
Console.WriteLine(kvp.Value);
}
Here is working demo link https://dotnetfiddle.net/MGkRIA

Related

Read JSON from string and get access to keys

Can I read JSON from string and iterate if I don't know what kind of key it stores?
Generally, it will be key value pair?
I know that I can use:
dynamic dynamicJson = JsonConvert.DeserializeObject(json);
But I don't have an access to keys.
I'm not trying to deserialize into strongly-typed .net objects.
You can use JObject.Parse method and iterate through KeyValuePair of JObject:
var jObject = JObject.Parse(json);
foreach (KeyValuePair<string, JToken> kvp in jObject)
{
// Your code.
}

How to get the deep level node value easily when we don't have the object class with fastjson

I need to parse lots of long json strings. Newtonsoft.Json is slow and I try to use fastjson.
I don't have the object class so I use the following code to get values when using Newtonsoft.Json:
JObject jo = (JObject)JsonConvert.DeserializeObject(addressBook);
string floor = jo["Street"]["building"]["floor"].ToString();
When I turn to use fastjson and use the JSON.Parse(string), I got an Dictionary<string, object>. And if I want to get the 'floor' value, I need to do the casting for each level like below:
var ob = (Dictionary<string, object>)JSON.Parse(addressBook);
var street = (Dictionary<string, object>)ob["Street"];
var building = (Dictionary<string, object>)street["building"];
var floor= (Dictionary<string, object>)building["floor"];
Does anyone know fastjson support it or not? And can it still be fast?

Deserialize JSON using C#

I am trying to deserialize this JSON string to different objects in C# using Newtonsoft.Json
{"apple":{"title":"apple","color":"red"},"banana":{"title":"banana","color":"yellow"}}
Note "apple" and "banana" in this example are dynamic values, so it's very well possible that suddenly it's called something others, e.g. ananas.
Now what I'm trying to do is deserialize this JSON string in a way that I can do a foreach loop through all the objects (Apple, Banana, ...) to read the value of the color field.
But apparently I'm doing something wrong, this is my code.
dynamic d = JObject.Parse(jsonString);
foreach (dynamic e in d)
{
Console.WriteLine(e.title);
}
Does anyone know why this does not work like this?
You want to do e.Value.title instead of just e.title.
DotNetFiddle example here.
e is a KeyValuePair<String,JToken> so we need to access e.Value to get the title.
var d = JObject.Parse(#"{""apple"":{""title"":""apple"",""color"":""red""},""banana"":{""title"":""banana"",""color"":""yellow""}}");
foreach (dynamic e in d)
{
Console.WriteLine(e.Value.title);
}
Try using System.Web.Script.Serialization then doing the following:
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string, dynamic>>(YOURJSON);
To use this do:
string item = dict["name"];
string itema = dict["item"]["thing"];
Hope this helps.

Read and save unknown key value pair in JSON

I am making an API call. On successful completion I know the structure of JSON response. I can read that and save it on DB using JSON.NET, but if the API calls generates error, a JSON of unknown structure is generated. I have to parse and save it in DB. How can I do that.
In genral structure of error response is this:
{"origin-of_error":"error_message"}
There are some cases though where additional key value is also present.
Since you don't know the exact contents of the JSON, but you at least know it is a flat object with key-value pairs, then I would recommend deserializing into a Dictionary<string, string>. You can then easily iterate over the key-value pairs to extract the data you need to store in the DB.
string json = #"
{
""origin-of_error"" : ""error_message"",
""foo"" : ""bar""
}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
foreach (KeyValuePair<string, string> kvp in dict)
{
Console.WriteLine(kvp.Key + ": " + kvp.Value);
}
try this
IDictionary<string, JToken> jsondata = JObject.Parse(json);
foreach (KeyValuePair<string, JToken> innerData in jsondata) {
Console.WriteLine("{0}=> {1}",innerData.Key, innerData.Value.ToString());
}

How to handle json object in codebehind

I have - var JsonObj = []; and I pushed some data into that and send it to codebehind using JQuery.ajax() method. I am able to receive in a method which has parameter like this
[WebMethod]
public static void SaveInfo(List<Object> userEnteredDetails)
{
}
And i loop thru the collection to get the data something like this,
foreach (object item in userEnteredDetails)
{
Dictionary<string, object> details = item as Dictionary<string, object>;
string name = details["customerName"] as string;
}
The problem here is, I am receiving more than 10 items in the collecton. So i cannot read another property in my above for loop. Something like this,
foreach (object item in userEnteredDetails)
{
Dictionary<string, object> details = item as Dictionary<string, object>;
string name = details["customerName"] as string;
string city= details["city"] as string;
}
Firsttime city wil throw an error, and next time customername. Because item variable will have one variable at a time. How to read all the more than 10 records efficiently since we dont have property, but can read only through an indexer (details["customerName"]).
Try this:
string name = String.Empty;
string city = String.Empty;
foreach (object item in userEnteredDetails)
{
Dictionary<string, object> details = item as Dictionary<string, object>;
if (details.ContainsKey("customerName"))
name = details["customerName"] as string;
if (details.ContainsKey("city"))
city= details["city"] as string;
}
You can enumerate the details Dictionary.
foreach(var kvp in details)
{
// do something with kvp.Key and kvp.Value
}
EDIT:
To get a one merged details dictionairy first, you can try this:
var details = list.Select(item => item as Dictionary<string, object>).SelectMany(d => d).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
One thing you could have a type with fields in them mapping to the list of objects. While making the ajax call stringify the json object. In your web method recieve it as string. Use Json Deserializer and deserialize it to the type you have created.
Theres a very flexible json framework (JSON.NET) which could help with this, definitley worth considering if your doing a lot of work with JSON http://json.codeplex.com/

Categories

Resources