JSON.net - deserialize varying objects into one object - c#

Sorry for the messy title, I'm not sure how I should explain it better.
The JSON string I have:
{
"Name that varies here": {
"id": 01,
"ArrayOfType": [{
"name": "a name",
"id": 01
},
{
"name": "a name",
"id": 02
}]
},
"Another name": {
"id": 02,
"ArrayOfSameType": [{
"name": "a name",
"id": 03
},
....
I dont know how I should deserialize it, especially because the Object-name varies. Basically what I'd want is a List where someObject has String name, int ID and a List.
How should I create the object and deserialize it? So far I have only deserialized arrays/objects that are all called the same. I could make a class for each name (Name that varies here.cs, Another name.cs) with the variables and then deserialize it into that class.

Related

Creation of Rule Class from the json in a generic way

I have a json like below and I am trying to create a class for this. What would be the best way to represent this.
For example : A Rule object consists of conditions, like "Any Condition" or "All condition" and they can nested like the below example.
A condition in its simplest form is Class with 3 properties : Fact, Operator, Value.
I am struggling with representing the All and Any Conditions which can be nested. Can some give some idea on how I can represent this in my Rule Class.
{
"conditions": {
"any": [{
"all": [{
"fact": "gameDuration",
"operator": "equal",
"value": 40
}, {
"fact": "personalFoulCount",
"operator": "greaterThanInclusive",
"value": 5
}]
}, {
"all": [{
"fact": "gameDuration",
"operator": "equal",
"value": 48
}, {
"fact": "personalFoulCount",
"operator": "greaterThanInclusive",
"value": 6
}]
}]
}
}

How do you dynamically parse, read, and append to JSON with multiple sub arrays

After a bunch of research I haven't been able to find any good ways to read a json file, store their values, then append a new object/array to it.
The JSON looks like
{
"Skywars": [
{
"Solo Normal": [
{
"000001": [
{
"Kills": 213,
"Deaths": 117
}
]
}
],
"Solo Insane": [
{
"000001": [
{
"Kills": 10790,
"Deaths": 7184
}
]
}
]
}
],"Bedwars": [
{
"Solo": [
{
"000001": [
{
"Kills": 0,
"Deaths": 0
}
]
}
],
"Duos": [
{
"000001": [
{
"Kills": 0,
"Deaths": 0
}
]
}
]
}
]
}
As an example, i am intending for it to go "Skywars.Solo Normal", "Skywars.Solo Insane", "Bedwars.Solo", "Bedwars.Duos" then append "000002" with new kills and deaths values.
For some reason, even after hours of searching, I can't find out how to read the kills and deaths (I've gotten close, using public Skywars[] Skywars { get;set; }. Problem is most of the examples are using JSON files that look like {"user":[{"id":1,"logins":0}]} with very little arrays & sub arrays.
To anyone who is kind enough to answer, please don't spoonfeed me code, explain how it would be done (would I need to create my own parser, etc), or if there are already any posts/links that answer my question (even though I failed to find how).
Notes -
"000001" and "000002" will be dynamic, so each time you start the program those values will be different. I just want to append after the last instance of stats saved.
Also sorry, I am still learning C# but know most of the basics and some more complex concepts, I've just never been good at storing data and using JSON. If you need anything to help else just add a comment and I'll add it.
Please see Json.NET's Modifying JSON.
This sample loads JSON, modifies JObject and JArray instances and then writes the JSON back out again.
Sample
string json = #"{
'channel': {
'title': 'Star Wars',
'link': 'http://www.starwars.com',
'description': 'Star Wars blog.',
'obsolete': 'Obsolete value',
'item': []
}
}";
JObject rss = JObject.Parse(json);
JObject channel = (JObject)rss["channel"];
channel["title"] = ((string)channel["title"]).ToUpper();
channel["description"] = ((string)channel["description"]).ToUpper();
channel.Property("obsolete").Remove();
channel.Property("description").AddAfterSelf(new JProperty("new", "New value"));
JArray item = (JArray)channel["item"];
item.Add("Item 1");
item.Add("Item 2");
Console.WriteLine(rss.ToString());
// {
// "channel": {
// "title": "STAR WARS",
// "link": "http://www.starwars.com",
// "description": "STAR WARS BLOG.",
// "new": "New value",
// "item": [
// "Item 1",
// "Item 2"
// ]
// }
// }

How to generate MSSQL Hierarchy ID for each element for a tree object

I've a requirement like dragable tree in my project.
I've successfully converted mssql resultset to json.
But the end user is again dragging and dropping and totally changed the tree structure.
Now I have the below json from the client.
[
{
"id": 1,
"title": "1. dragon-breath",
"items": [
{
"id": 10,
"title": "1. dragon-breath.1",
"items": [
{
"id": 100,
"title": "1. dragon-breath.1.2",
"items": [
{
"id": 1000,
"title": "1. dragon-breath.1.2.3",
"items": [],
"pos": 3
}
],
"pos": 2
},
{
"id": 101,
"title": "1. dragon-breath.1.2",
"items": [],
"pos": 2
}
],
"pos": 1
}
],
"pos": 1
},
{
"id": 102,
"title": "1. dragon-breath.1.2",
"items": [
{
"id": 1020,
"title": "1. dragon-breath.1.2.1",
"items": [],
"pos": 1
}
],
"pos": 2
},
{
"id": 1021,
"title": "1. dragon-breath.1.2.1",
"items": [],
"pos": 1
}
]
From the above json "pos" property is for MSSQL Hierarchyid value.
I am trying to regenerate the hierarchy id of each element, when this json posted back from the client.
I am requesting you people to help me. (spend 2 days no luck)
Following the link you posted to the other SO question, and then a link from a comment, I see you are using the MSSQL hierarchyid data type (hint: it might have helped if you been a bit clearer about that in your question ;)
From the online help I see there is a Parse function, which takes a string.
So you need to traverse your JSON tree structure, building strings for each element in the form /1/1/3/ for example, and pass those back to your database along with the associated node id.

Convert json string to value

I have two json string and also posted here. First json string convert from c# data table using newtonsoft dll. The second one is manual string. If i use the second string means chart displayed well. First one means chart not displayed. I just found the error "value" and "y" like a string in first json string. Kindly help me to change the first one to second one.
1)
[
{
"name": "CHE-CORPORATE",
"value": "42",
"y": "11.8"
},
{
"name": "CHE-TELUGU",
"value": "123",
"y": "10.8"
},
{
"name": "CHE-MALAYALAM",
"value": "13",
"y": "23.8"
}
]
2)
[
{ "name": "CHE-TELUGU",
"value": 123,
"y": 10.8
},
{
"name": "CHE-CORPORATE",
"value": 45,
"y": 40.8
},
{
"name": "CHE-MALAYALAM",
"value": 155,
"y": 12.8
}
]
Just convert the string to number
$.each(data,function(key,val){
val.value=+val.value; // convert the string to number
val.y=+val.y;
});
console.log(data);
Demo

Get JSON object node

I have a json object and I want to get the value of :
entities > media > sizes > large > h
Is there a way to get it like XML -> Xpath method?
This is extra lines that is irrelevant to question just because of ...
{
"created_at": "Sun, 01 Jan 2012 17:05:32 +0000",
"entities": {
"user_mentions": [
{
"screen_name": "nurdanterbiyik",
"name": "nurdan",
"id": 264782080,
"id_str": "264782080",
"indices": [
0,
15
]
}
],
"media": [
{
"id": 153522253777219584,
"id_str": "153522253777219584",
"indices": [
44,
64
],
"media_url": "http://p.twimg.com/AiFrrSmCMAAdEID.jpg",
"media_url_https": "https://p.twimg.com/AiFrrSmCMAAdEID.jpg",
"url": "http://t.co/ZwHN9gvO",
"display_url": "pic.twitter.com/ZwHN9gvO",
"expanded_url": "http://twitter.com/emelkiraac/status/153522253773025280/photo/1",
"type": "photo",
"sizes": {
"large": {
"w": 536,
"h": 800,
"resize": "fit"
},
Using JSON.NET you have several ways to read data without having to deserialize your JSON text into objects. Here is a simplified example:
string json = #" {
""created_at"": ""Sun, 01 Jan 2012 17:05:32 +0000"",
""entities"": {
""media"": [{
""type"": ""photo"",
""sizes"": {
""large"": {
""w"": 536,
""h"": 800,
""resize"": ""fit""
}
}
}]
}
}
";
JObject o = JObject.Parse(json);
int h = (int)o["entities"]["media"][0]["sizes"]["large"]["h"];
int h2 = (int)o.SelectToken("entities.media[0].sizes.large.h");
I prefer to think of JSON purely as serialized objects--the first and last thing I want to do with it is to de-serialize it into the objects that I then work with.
I can't tell you the best way to do it in c#, but I've had good luck using JSON.NET
JSON.NET will also let you (quote from website) "LINQ to JSON is good for situations where you are only interested in getting values from JSON, you don't have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects. LINQ to JSON allows you to easily read, create and modify JSON in .NET.", which sounds like what you are trying to do. I've never tried it, but if all you're trying to do is get one piece of data out of that long string, then it sounds like a good alternative.

Categories

Resources