How to deserialize only part of the json document? [duplicate] - c#

This question already has answers here:
Deserializing just a single node of a JSON response
(2 answers)
Closed 4 years ago.
Using Json.Net on dotnet core v3 preview.
The json looks similar to:
{
"rootElement": {
"id": 500,
"name": "water balloon"
}
}
I would like to deserialize this into an object that looks like:
public class Item {
public int id {get;set;}
public string name {get;set;}
}
instead of the much more annoying:
public class ItemWrapper {
public Item rootElement {get;set;}
}
This is obviously a contrived example, but it illustrated the problem. The actual Item class is far more complicated. And there are many of them. So I'm trying to identify a solution that will work for any json document that has this general format with a root node followed by the object I am actually interested in.
Any thoughts?

You can use JObject.Parse from Newtonsoft.Json.Linq namespace, and get your item like so:
var obj = JObject.Parse("json");
var item = obj["rootElement"].ToObject<Item>();

Related

How to parse multilayered JSON object? [duplicate]

This question already has answers here:
Create a strongly typed c# object from json object with ID as the name
(1 answer)
How can I parse a JSON string that would cause illegal C# identifiers?
(3 answers)
Closed 11 months ago.
I receive the following kind of response after a JSON request:
{
participants:{
"0":{
"name":"Name1",
"lastname": "lastname",
"email":"last#name.com",
"id":"12345"
},
"1":{
"name":"Name2",
"lastname": "lastname2",
"email":"last#name2.de",
"id":"72382"
}
}
}
So far only way I found so far to deserialize this is like this:
using System;
using Newtonsoft.Json;
namespace JSONParse
{
public class Root
{
public object participants { get; set; }
}
class MainClass
{
public static void Main(string[] args)
{
var myJson = JsonConvert.DeserializeObject<Root>(jsonMsg);
//Do stuff with it
Console.WriteLine(myJson.participants.ToString());
Console.ReadLine();
}
private static string jsonMsg = #"{
participants:{
""0"":{
""name"":""Name1"",
""lastname"": ""lastname"",
""email"":""last#name.de"",
""id"":""12345""
},
""1"":{
""name"":""Name2"",
""lastname"": ""lastname2"",
""email"":""last#name2.de"",
""id"":""72382""
}
}
}";
}
}
I've tried parsing it as both an array and a list, but this fails as this object is neither. It looks like a "de-arrayed array", so to speak.
The other, not practical, solution I found would be to create a new class for every possible key inside the response. But since the real data can have a possible unlimited number of keys, this is out of the question. It's not feasible to create an infinite amount of identical classes, all conveniently namend 0 to infinity.
How can I parse this response, so I can access the information correctly from within my code?

Deserialize the json to c# object [duplicate]

This question already has answers here:
How can I parse a JSON string that would cause illegal C# identifiers?
(3 answers)
Convert JSON with illegal characters in property name [duplicate]
(1 answer)
Closed 2 years ago.
{
"0": {
"no": "tenon",
"title": "ProdtesterTITLE439",
"stock": 12
},
"success": 1
}
I want to desrialize those json.The problem is I cant create class with name 0 in c sharp.i have tried
[JsonObject(Title = "0")]
and
[DataContract(Name ="0")]
Not one of them are worked.
Good news! Your root object doesn't have a name, so you don't need to create a class with that name. 0 is a property of the root object.
Of course, 0 isn't a valid property name in C# either. That's where JsonPropertyAttribute comes in:
public class RootObject
{
[JsonProperty("0")]
public MyData Data {get;set;}
public bool Success {get;set;}
}
public class MyData
{
public int Stock {get;set;}
// other properties
}

How to deserialize a json data array [duplicate]

This question already has answers here:
How to deserialize a JSON array into an object using Json.Net?
(2 answers)
Serializing/deserializing arrays with mixed types using Json.NET
(1 answer)
Closed 3 years ago.
I have this json file:
{
"timestamp": 1557323147422,
"change_id": 11687520784,
"data": [
[ "new", 5775.0, 16530.0 ],
[ "new", 5774.5, 360.0 ]
]
}
I need to set up a class to deserialize it, but the data array is causing me a problem.
I tried to map data to:
List<(string, double, double)>
but that doesn't work.
List works, but then it's just pushing the problem one step away.
I can map it to
List<dynamic>
and then I get a list of JArray that I need to parse individually.
What I need is to be able to map it to some class that has a string and 2 doubles.
You can use http://json2csharp.com/
I generated this code:
public class RootObject
{
public long timestamp { get; set; }
public long change_id { get; set; }
public List<List<object>> data { get; set; }
}
Your array is still an array of object in JSON, it is neither a tuple nor a type.
So List<List<object>> (or IEnumerable<IEnumerable<object>>) seems to be the only option.

Parse json name begins with number in C# by Json.net - Newtonsoft [duplicate]

This question already has answers here:
Deserialize json that has some property name starting with a number
(2 answers)
Closed 5 years ago.
I need to parse JSON file in C# code by using JSON.net (Newtonsoft)
But json file I receive begins as this:
{"3h":3}
the variable name begins with number but c# can't do like this.
How can I set the value in the right way? Should I swap the variable name by my self? That would make very dirty code.
Thank you.
You can do this little focus with mapping:
class Program
{
static void Main(string[] args)
{
string jsonInput = #"{""3h"":3}";
var result = (myJsonObj)JsonConvert.DeserializeObject<myJsonObj>(jsonInput);
Console.WriteLine(result.MyProperty);
}
}
public class myJsonObj
{
[JsonProperty(PropertyName = "3h")]
public string MyProperty { get; set; }
}

Conditionally deserialize JSON string or array property to C# object using JSON.NET? [duplicate]

This question already has answers here:
How to handle both a single item and an array for the same property using JSON.net
(9 answers)
Closed 6 years ago.
I have a defined C# object based off a very complex JSON I'm getting from a third party API. Here's a piece of it:
{"alarmSummary":"NONE"}
The corresponding property in C# would be:
public string alarmSummary {get; set;}
And I would get this converted by using my typical JSONConvert from JSON.NET:
var alarms = JSONConvert.DeserializeObject<MyClass>(jsonString);
However, the API will put alarms in this format, as an array, and "NONE" when there aren't any as a string:
{"alarmSummary" : ["AHHH Something went wrong!!", "I'm on fire!!"]}
Which means in C# it would need to be:
public string[] alarmSummary {get; set;}
If I could, I would just have the JSONConvert deserialize the "NONE" string into an array of just one entry. Is there a way to set conditions on this property, or will I have to take the whole complex JSON string and hand convert it?
This one should be easy - you can set your alarmSummary as object and then have separate property that evaluates alarmSummary and returns null or array depending on the value.
public object alarmSummary { get; set; }
protected string[] alarmSummaryCasted
{
get
{
if (alarmSummary is String)
return null;
else
return (string[]) alarmSummary;
}
}
If you are expecting only those two combinations, you could make use of the dynamic keyword and check deserialized object:
string json = "{\"alarmSummary\":\"NONE\"}";
//string json = "{\"alarmSummary\" : [\"AHHH Something went wrong!!\", \"I'm on fire!!\"]}";
string[] alarmSummary;
dynamic obj = JsonConvert.DeserializeObject(json);
if (obj.alarmSummary.Type == JTokenType.Array)
alarmSummary = obj.alarmSummary.ToObject<string[]>();
else
alarmSummary = new[] { (string)obj.alarmSummary.ToObject<string>() };

Categories