Deserialize complex JSON data in C# - c#

I'm just an amateur in C# programming. Now i have a JSON data that looks like following
{
type: "xxx",
width: "xxx",
dataSource: {
"chart": {
"caption": "xxx"
},
"data": [
{},
{}
]
}
}
I'm having the whole data as escaped string. now after Unescape when I'm using JavaScriptSerializer as follows
var data = ser.Deserialize<Dictionary<String, Object>>(chartData);
I'm able to get the "type", "width" as
data["width"]
data["type"]
Now I have to get the value of "caption". Any suggestion how to get that, I believe the dictionary structure need to be changed but I'm stacked for my lack of knowledge in C#

If you know the object's scheme you man want to create a class that represents in and then deserialize the json into it:
YourKnownClass obj = JsonConvert.DeserializeObject<YourKnownClass>(json);
Console.WriteLine(obj.dataSource.chart.caption.Value);
Another option is by using a dynamic type (There is no good reason using a dynamic object if you know the schema and can create a matching C# class. This has a performance impact as well):
dynamic obj = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(obj.dataSource.chart.caption.Value);
BTW, In this example i'm using json.net which is a popular library.

Related

C# Merge two json and remove missing property

i am working with two unknown json (i don't know structure) and i need to merge these two, i also have to remove missing properties, I know I probably haven't explained myself very well, so I'll give you an example.
Json 1:
{
'FullName': 'Dan Deleted',
'Deleted': true,
'DeletedDate': '2013-01-20T00:00:00',
'location': {
'nation': 'it',
'city': 'Madrid'
}
}
Json 2:
{
'FullName': 'Dan',
'Age': '23',
'DeletedDate': '2014-01-20T00:00:00',
'location': {
'nation': 'es'
}
what I would:
{
'FullName': 'Dan',
'Deleted': true,
'DeletedDate': '2014-01-20T00:00:00',
'location': {
'nation': 'es',
'city': 'Madrid'
}
}
I'm using Newtonsoft.Json and i've saw that there is a method merge json1.merge(json2) but in this way i will get something like that:
{
"FullName": "Dan",
"Deleted": true,
"DeletedDate": "2014-01-20T00:00:00",
"location": {
"nation": "es",
"city": "Madrid"
},
"Age": "23"
}
I hope you understand.
In practice I would like that if the property is present in both json, in the result the value is that of json2, but if a property is present only in json2, in the result this should not be there. While if it is only in json1 then it will be in the result.
How could I do?
Thank you very much!😃😃
According to Newtonsoft's example its a matter of which JObject it is invoked on and which other JObject is passed in as an argument. The one passed in by argument is the one that overwrites. Given these parameters, you will want to get the API responses as a string and then deserialize with JObject.Parse(string)
Also note that prior to the merge you can probably run some validation logic on these parsed objects to suit your needs
You should probably also explore the JsonMergeSettings object that is shown in the example, as it may include some finer grained options that you may want for your merge

How to extract a dataset from Json where the element is fluid

I have a Json object coming into my WebApi. The structure can take any form. The only thing I know for certain is that somewhere in that structure (could be a top level node, could be a child node) I will have a node made up of:
"data": {
"mop": "1012346354462",
"fuelType": "E",
"Id": "1029dd56-10b1-46cb-9966-3c37e057a470",
"Status": "SecuredActive",
"StatusFromDate": "2020-11-20T17:00:00.000Z",
"ActiveDate": "2020-11-21T00:00:00.000Z",
"GeneratedReference": "1012346354462_1"
},
Can anyone help on how I can easily extract this bit of data from the JSon Object. I have a class that maps to these properties, but before I can use it I need to single this out from the rest of the JSON. I'm using C#
After much playing around, I've finally found a solution, so thought I'd post in-case others hit a similar issue.
JObject result = JObject.Parse(Request.ToString());
var clientarray = result["events"].Value<JArray>();
var blockIwant = clientarray.Children<JObject>().Select(x => x.Children<JProperty>().Where(y => y.Name == "data").First());
use JSON Convert to deserialize the object.
var Data = JsonConvert.DeserializeObject<dynamic>(data);
Then you can access using the Data object.
Eg : Console.WriteLine((String)Data.data.fuelTypereturn);
Gives the answer as "E"

How to check In C# JArray have specific key pair

I am working on JArray in .NET CORE and I am getting random structure of this one specific key, hence getting different error. I need to know if JArray has specific child Array and if Child JArray have specific key pair (NOT VALUE) i.e. value{ "Id":""} one of error is following;
Accessed JArray values with invalid key value: "id". Int32 array index expected.
at Newtonsoft.Json.Linq.JArray.get_Item(Object key) at
the standard structure I am expecting is as following;
{[value, [
{
"id": "7ef82869-e235-69a2-f81e-3a9664e89bc4",
"value": ""
}
]]}
sometime I get as, meaning throw null error where I am trying to map Id.
{[value, [
{
"value": ""
}
]]}
and some Time I don't get this property at all
I am trying following check to cover all scenario but Its not really working.
code
if (answerItems.value != null && answerItems.value.HasValues && answerItems.value["id"]!=null)
{
I received some constructive criticism on the brevity of my answer so I figured I would elaborate to help you through your issue.
First, let's take a look at your JSON. In short, it isn't valid. In fact, it isn't even close to valid JSON. I can only assume you meant something like this:
{
"values" : [{ "id" : "7ef82869-e235-69a2-f81e-3a9664e89bc4", "value": "" }]
}
I would suggest that anytime you are trying to parse data like this and you run into issues you start trouble shooting by validating the data itself. I like to use JSONLint for this.
Next, it is difficult from your example code to tell exactly what you are trying to do. I can only guess that you are attempting to use the dynamic object method of parsing and working with the data. A downside to this method is it is difficult to validate your data before you work with it.
Instead, I would use the Newtonsoft.Json.Linq.JObject.Parse method. This gives you some tools for working with and validating the information. Below I have included a very simple example of how this would be done.
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string json = "{ \"values\": [{ \"id\": \"7ef82869-e235-69a2-f81e-3a9664e89bc4\", \"value\": \"\" }] }";
JObject obj = JObject.Parse(json);
// Check to see if we got our value array
if (obj.ContainsKey("values")) {
JArray values = (JArray)obj["values"];
// Do we have any values in our array?
if (values.Count > 0) {
JObject firstItem = (JObject)values[0];
// We check to see if we have an ID parameter
if (firstItem.ContainsKey("id")) {
Console.WriteLine(firstItem["id"]);
}
}
}
}
}
As I mentioned in my original post, I would strongly recommend reviewing the Newtonsoft.Json documentation.

Dealing with a JSON object's property called "private" in C# with Newtonsoft's JSON.NET

I am trying to parse a json string returned from the xively feed from an Air Quality Egg. One of the properties says whether the xively feed is public or private. The property is called private and takes the string value "true" or "false". To get data from the feed I am calling xively's Historical Data REST API which successfully returns me valid JSON. I am then using JSON.NET to parse the JSON in C#. My parsing starts thus:
dynamic historicalDatapoints = JValue.Parse(jsonString) as JObject;
if (historicalDatapoints != null)
{
var id = historicalDatapoints.id;
var title = historicalDatapoints.title.ToString();
var privacy = bool.Parse(historicalDatapoints.private.ToString())
// More parsing
}
I have a problem with that last line of code. C# will not let me refer to the property called "private". Here's the corresponding (redacted) JSON:
{
"id": 000000843,
"title": "Blah Road Egg 02",
"private": "false",
//...
}
Using JSON.NET how should I parse out the property private?
Try historicalDatapoints.#private to access that value. If that doesn't work then you could also try historicalDatapoints["private"]

Parsing Facebook Open Graph API JSON Response in C#

I try to get parse JSON response for the following link:
https://graph.facebook.com/feed/?ids=135395949809348,149531474996&access_token=
The response is like that:
{
"135395949809348": {
"data": [
{
....Some data
}]
}
,
"325475509465": {
"data": [
{
....Some data......
}]
}
}
I use System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(string json) method.
But the objects key names always different , so I can't define the class that can be used for parsing this response.
Is anyone has any experience in parsing multiple id's response from Facebook?
With JSON.NET you can read the respose as JObject and then access it via indexer.
var json = JObject.Parse(result);
var array = json["325475509465"]["data"];
Then you can deserialize objects from array...
What is your issue with the Deserialize? Deserialize is going to produce a Dictionary, with potential inner arrays and dictionary instances too....
It wouldn't parse as a custom object unless you build a serializer to do that... or look at JSON.NET: http://james.newtonking.com/pages/json-net.aspx

Categories