How to deserialize a json data array [duplicate] - c#

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.

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?

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

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

Unity C#: parse JSON file into data structure [duplicate]

This question already has answers here:
Serialize and Deserialize Json and Json Array in Unity
(9 answers)
Closed 5 years ago.
I'm trying to create a custom revision quiz program in Unity C# which allows users to load questions into the program using JSON files, structured as below:
{
"question": [
{
"title": "What wave characteristic is measured on the vertical axis?",
"answers": {
"correct": "Amplitude",
"wrong": [
"Frequency",
"Period",
"Speed"
]
}
},
{
"title": "Which of these is a vector quantity?",
"answers": {
"correct": "Velocity",
"wrong": [
"Speed",
"Time",
"Mass"
]
}
}
]
}
I've managed to get my program reading from a file using a StreamReader, but am having a lot of trouble trying to get it into a single data structure.
I have seen other solutions using classes and manually defining structures for their solutions, but I don't know how to go about implementing this for a) as complex a structure as this and b) a structure that can have an arbritrary number of items in it (I'd like to support any number of questions). If the best way is to define these classes, how do I go about referencing items inside them? In the past I've parsed JSON using Python 3.6's json library's json.loads() function, and that worked perfectly, creating a single multidimensional array / dictionary structure that I could work with easily.
To put it simply, I currently have a string that I've read from a file with JSON data in it. How do I synthesise this into a single array that I can easily access using, eg, questions[question][0]["title"], which would return "What wave characteristic is measured on the vertical axis?" in the above case?
Use this site and generate your model.
public class Answers
{
public string correct { get; set; }
public List<string> wrong { get; set; }
}
public class Question
{
public string title { get; set; }
public Answers answers { get; set; }
}
public class RootObject
{
public List<Question> question { get; set; }
}
var model = JsonConvert.DeserializeObject<RootObject>(jsonstring);
That is all
BTW: You can also access to those properties dynamically without declaring any model
var model = JObject.Parse(jsonstring);
var title0 = (string)model["question"][0]["title"];
PS: I used Json.net
I think one way you can create a single data structure in your application by using the JSON given above is using the "paste special feature" of visual studio.Once you select it from the edit menu you have option to create class from JSON by just pasting any valid JSON.
I get the following class after pasting your JSON related to Questions:-
public class Rootobject
{
public Question[] question { get; set; }
}
public class Question
{
public string title { get; set; }
public Answers answers { get; set; }
}
public class Answers
{
public string correct { get; set; }
public string[] wrong { get; set; }
}
Single Rootobject class consists of the Question array.There different classes automatically created by visual studio related to Question and Answers.
You can deserialize the JSON values into your RootObject using JSON.NET desrialization:
var questions= JsonConvert.DeserializeObject<RootObject>(jsonString);

Cannot deserialze the current JSON array into type

I'm trying to deserialize following JSON data :
{
"bids": [
[
"392031.00000000",
"0.00254444"
],
[
"390000.00000000",
"0.52917503"
],
......
],
"asks": [
[
"392999.00000000",
"1.00000000"
],
[
"393000.00000000",
"0.31572236"
],
.....
]
}
I've looked into similar question such as this one, but I'm not getting close result and also noticed that in that question the structure of JSON is not similar.
My code for deserialization is as below
public class OrderBookElement
{
// I've also tried below commented code
//[JsonProperty(PropertyName = "0")]
//public double price { get; set; }
//[JsonProperty(PropertyName = "1")]
//public double volume { get; set; }
List<double> values;
}
public class OrderBookResponse
{
[JsonProperty(PropertyName = "bids")]
List<OrderBookElement> bids { get; set; }
[JsonProperty(PropertyName = "asks")]
List<OrderBookElement> asks { get; set; }
}
Below is code that I use for deserialization
var ordBook = JsonConvert.DeserializeObject<OrderBookResponse>(jsonResponse);
This gives me error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'RestAPI.OrderBookElement' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
The JSON you've shown would be represented by:
public class OrderBookResponse
{
[JsonProperty("bids")]
public List<List<string>> Bids { get; set; }
[JsonProperty("asks")]
public List<List<string>> Asks { get; set; }
}
The bids and asks properties in the JSON are each just an array of arrays of strings.
I'd suggest deserializing to a model which matches the JSON, then convert that into a more useful model separately. It may be possible to apply attributes to your class to persuade Json.NET to do what you want, but I tend to think that by the time there's a significant discrepancy (not just the property names), it's worth separating the two models out, one for serialization and one for use within the rest of your code.

How should one interpret this JSON structure?

I've just started to work with JSON and after having read a few articles, I'm still unclear if I'm looking at an array, list or just an object. It looks like this.
{
"list": [{
"fields": {
"id": "9222115557374550596",
...
},
},
{
"fields": {
"id": "9222115557374550597",
...
},
}],
"paging": {
"pageCurrent": 0,
"itemMin": 0,
"itemMax": 2,
"maxNextPages": 0,
"pageSize": 100
}
}
I'd like to deserialize it to be a list (or IEnumerable) of objects typed so that there's an Id property (perhaps not all fields have to be parsed in to the object).
When I try to do that using the following code:
List<Some> somes = JsonConvert.DeserializeObject<List<Some>>(dataAbove);
class Some { public String Id { get; set; } }
I get a long error message about me not being using the correct type and array and a bunch of other stuff that makes me confused. Am I on the right track or did I totally went off and got lost?!
I understand it's something with the list at the root. But what?! Or at least - what should I google for?!
Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[ScriveProxy.Template]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\u000d\u000aTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\u000d\u000aPath 'list', line 1, position 8."
It can't be this one because the outer brackets are curly not squary...
In this solution, we end up with a single object, not an array, so it's not what I'm aiming for neither.
In your case, "list" is an array of "fields" objects.
"paging" is an object.
Both "list"` and "paging"` are in an un-named root object.
Working dotNetFiddle: https://dotnetfiddle.net/4qLTvq
See the output in the console pane of the fiddle above.
Here's How you should declare your Classes for Deserializing this particular JSON into C# Classes.
public class Fields
{
public string id { get; set; }
}
public class TheFields
{
public Fields fields { get; set; }
}
public class Paging
{
public int pageCurrent { get; set; }
public int itemMin { get; set; }
public int itemMax { get; set; }
public int maxNextPages { get; set; }
public int pageSize { get; set; }
}
public class RootObject
{
[Newtonsoft.Json.JsonPropertyAttribute("list")]
public List<TheFields> FieldsList { get; set; }
public Paging paging { get; set; }
}
And here's how you would deserialize the whole thing.
var rootObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
Since List is a keyword, and to avoid confusion and collision, I changed it's Name to FieldsList and also renamed the List class to TheFields class. You may choose any other name(s) that you feel is appropriate.
Explanation on Object vs Array
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
Source: http://www.json.org/
If it starts with { it's an object.
If it starts with [ it's an array.

Categories