Read and save unknown key value pair in JSON - c#

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());
}

Related

Request.Form serialize to JSON and loop through all properties in JSON

I have .NET Core Web API project and one API query that accepts random form data (without files). I need to serialize form data to JSON and pass to the service. Then in service I need to loop through each JSON property and do some handling.
I'm trying something like this:
var json = JsonConvert.SerializeObject(Request.Form); //it isn't simple JSON
and
var jsonObject = new JObject();
var data = Request.Form.ToList();
for (var i = 0; i < data.Count; i++)
{
jsonObject.Add(data[i].Key, data[i].Value.ToString());
}
Are there any other ways to do that? What about loop through all JSON properties?
I am not sure you can serialize directly Request.Form to JSON.
But could you try like this way ?
public static IDictionary<string, object> ToDictionary(this NameValueCollection col)
{
var dict = new Dictionary<string, object>();
foreach (var key in col.Keys)
{
dict.Add(key, col[key]);
}
return dict;
}
then
var dictionary = Request.Form.ToDictionary();
string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
then on the service deserialize your string.
Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

Deserialising a list of lists where outer list has no identifier without hard coding [duplicate]

I'm quite new to JSON, and am currently learning about (de)serialization.
I'm retrieving a JSON string from a webpage and trying to deserialize it into an object. Problem is, the root json key is static, but the underlying keys are dynamic and I cannot anticipate them to deserialize. Here is a mini example of the string :
{
"daily": {
"1337990400000": 443447,
"1338076800000": 444693,
"1338163200000": 452282,
"1338249600000": 462189,
"1338336000000": 466626
}
}
For another JSON string in my application, I was using a JavascriptSerializer and anticipating the keys using class structure. What's the best way to go about deserializing this string into an object?
Seriously, no need to go down the dynamic route; use
var deser = new JavaScriptSerializer()
.Deserialize<Dictionary<string, Dictionary<string, int>>>(val);
var justDaily = deser["daily"];
to get a dictionary, and then you can e.g.
foreach (string key in justDaily.Keys)
Console.WriteLine(key + ": " + justDaily[key]);
to get the keys present and the corresponding values.
You can use dynamic in .NET 4 or later. For example with JSON.NET I can do:
dynamic obj = JsonConvert.Deserialize<dynamic>("{x: 'hello'}");
You can then do:
var str = obj.x;
However, unsure how it will handle numeric keys. You can of course just use JObject directly itself, for example:
var obj = JObject.Parse("{'123456': 'help'}");
var str = obj["123456"];
Whenever you have JSON with dynamic keys it can usually be deserialized into a Dictionary<string, SomeObject>. Since the inner JSON keys are dynamic (in this question) the JSON can be modelled as:
Dictionary<string, Dictionary<string, int>>
I would recommend using NewtonSoft.Json (JSON.Net) or System.Text.Json (if you're working in .NET-Core 3.0 and up).
Newtonsoft.Json
Use DeserializeObject<T> from JsonConvert:
var response = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, int>>>(json);
System.Text.Json
Use Deserialize<T> from JsonSerializer:
var response = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, int>>>(json);
This is not convenient to use, because in с# can not be defined a variable starts with a number. Add prefix to keys.
Or try this:
string json = "
{ daily:[
{ key: '1337990400000', val:443447 },
{ key: '1338076800000', val:444693 },
{ key: '1338163200000', val:452282 },
{ key: '1338249600000', val:462189 },
{ key: '1338336000000', val:466626 }]
}";
public class itemClass
{
public string key; // or int
public int val;
}
public class items
{
public itemClass[] daily;
}
items daily = (new JavascriptSerializer()).Deserialize<items>(json);
Then you can:
var itemValue = items.Where(x=>x.key=='1338163200000').Select(x=>x.val).FirstOrDefault();

Need help to deserialize JSON string in 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

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 convert the following JSON array into IDictionary<string, object>?

Following is the serialized JSON array I want to convert to IDictionary
[
{
"8475": 25532
},
{
"243": 521
},
{
"3778": 15891
},
{
"3733": 15713
}
]
When I tried to use
JsonConvert.DeserializeObject<IDictionary<string, object>>((string)jarray);
I got an error saying:
Cannot cast 'jarray' (which has an actual type of 'Newtonsoft.Json.Linq.JArray') to 'string'
The JSON deserializer requires only a string.
If you already have the JArray, all you have to do is convert it to a dictionary I guess.
Roughly something like this:
IDictionary<string,object> dict = jarray.ToDictionary(k=>((JObject)k).Properties().First().Name, v=> v.Values().First().Value<object>());
Check this for complete code with an example
I think there might be a better way to convert it to a dictionary though. I'll keep looking.
the JsonConvert.DeserializeObject<T> Method takes a JSON string, in other words a serialized object.
You have a deserialized object, so you'll have to serialize it first, which is actually pointless, considering you have all the information you need right there in the JArray object. If you are aiming just to get the objects from the array as key value pairs, you can do something like this:
Dictionary<string, object> myDictionary = new Dictionary<string, object>();
foreach (JObject content in jarray.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
myDictionary.Add(prop.Name, prop.Value);
}
}
To turn your JArray into a string, you'll need to assign the key & values of the dictionary for each element. Mario gave a very accurate approach. But there's a somewhat prettier approach as long as you know how to convert each item into your desired type. The below example is for Dictionary<string, string> but can be applied to any Value type.
//Dictionary<string, string>
var dict = jArray.First() //First() is only necessary if embedded in a json object
.Cast<JProperty>()
.ToDictionary(item => item.Name,
item => item.Value.ToString()); //can be modified for your desired type

Categories

Resources