i got this question i don't know is it possible or not.
so i am getting this json data
{
"data": {
"student_score": {
"time_elapsed": 10,
"right_moves": 20,
"wrong_moves": 10,
"score": 166
},
"average_score": {
"time_elapsed": 10,
"right_moves": 20,
"wrong_moves": 10,
"score": 166
},
"total_student_count": 1
},
"status": "success",
"time": 1379066567
}
i am able to coveting it to two class objects of these classes..
public class StudentAssignementScoreClassForCompAssn : ViewModelBase
{
private int _time_elapsed;
private int _right_moves;
private int _wrong_moves;
private int _score;
public int time_elasped
{
get
{
return _time_elapsed;
}
set
{
_time_elapsed = value;
RaisePropertyChanged("time_elapsed");
}
}
public int right_moves
{
get
{
return _right_moves;
}
set
{
_right_moves = value;
RaisePropertyChanged("right_moves");
}
}
public int wrong_moves
{
get
{
return _wrong_moves;
}
set
{
_wrong_moves = value;
RaisePropertyChanged("wrong_moves");
}
}
public int score
{
get
{
return _score;
}
set
{
_score = value;
RaisePropertyChanged("score");
}
}
}
second class is same as it is..but with different name..
so my problem is this..the structure of the json data is variable like data fields may be more or less..so is there any way that i automatically create class of this data and can bind all the fields of this class(automatically :))..means data filling and binding with the view that does not depend on how the json coming( i will have separate file for the details of json format) ..i think you are getting my issue..any kind of help like idea or different way of working with json (anything) is appreciated..sorry for my bad english :(
Look at this. http://jsonclassgenerator.codeplex.com/SourceControl/latest
Also see this SO answer: Deserialize JSON into C# dynamic object?
There are so many results:
search?q=dynamically+create+c%23+class+from+json
You need to create 2 more class like
public class YourClass
{
public DataClass data {get;set;}
public string status {get;set;}
public long time {get;set;}
}
public class DataClass
{
public StudentAssignementScoreClassForCompAssn student_score {get;set;}
public StudentAssignementScoreClassForCompAssn average_score {get;set;}
public int total_student_count {get;set;}
}
then use Newtonsoft.Json for conversion
JsonConvert.DeserializeObject<YourClass>(inputString)
Related
I've been trying to get data from a JSON file with VScode. I made some classes and can use some of the values saved in the different classes. My problem right now is, that I got a Class which contains a List within a List... How can I get this value? Got some Code-example. Thank you in advance for your help:
namespace TestDeserialize
{
public class DataInfo
{
[JsonProperty("Sample rate")]
public int SampleRate { get; set; }
}
public class Datum
{
public string Trigger { get; set; }
[JsonProperty("Channel :AS_V[mm]")]
public List<List<double>> ChannelASVMm { get; set; } //Want to get those values
}
public class Root
{
public DataInfo Data_info { get; set; }
public List<Datum> Data { get; set; }
}
public class Program
{
public static void Main()
{
string filename2 = #"C:\Users\10606167\TestDatenAbstand.json";
Root datum = JsonConvert.DeserializeObject<Root>(File.ReadAllText(filename2));
Console.WriteLine($"Samplerate: {datum.Data_info.SampleRate}");
}
}
}
This is my JSON-File:
{"Data_info":{"File name":"C:\\Dewesoft\\Data\\Test(2).dxd","Start time":"22.08.2022","Number of channels":1,"Sample rate":100,"Reduced rate":10},
"Events":[{"Event Type:":1,"Event :":"Speicherung gestartet um","Time:":0,"Comment:":""},{"Event Type:":2,"Event :":"Speicherung gestoppt um","Time:":1.72,"Comment:":""}]
, "Data":[
{
"Trigger" : "Data1",
"Channel :AS_V[mm]":[
[0, 1.57027852535248]
]
}]}
I can get the value of my samplerate but I dont know how to get the value of ChannelASVm...
If you simply want the first value of the first List of the first Datum in your Root class, you just have to do something like this :
public class Program
{
public static void Main()
{
string filename2 = #"C:\Users\10606167\TestDatenAbstand.json";
Root datum = JsonConvert.DeserializeObject<Root>(File.ReadAllText(filename2));
double valueInListOfList = datum.Data[0].ChannelASVMm[0][0];
}
}
To target an element in a List inside another List by using indexes, you just have to chain [] like this : [<indexOfFirstList>][<indexOfSecondList>]
If you want to target specific Datum instances and specific double values in ChannelASVm, you will have to add some conditions to be able to target exactly what instances/values you want.
For that you can take a look at some Linq functions :
Single
First
Where
Or simply do a foreach and extract the data you need, but I recommend to use Linq instead
if you need just Channel :AS_V[mm], you don't need any classes
List<double> channel = JObject.Parse(json)["Data"]
.SelectMany(x => x["Channel :AS_V[mm]"]).First().ToObject<List<Double>>();
or you can use classes
List<List<double>> channelASVMm = datum.Data.SelectMany(x=> x.ChannelASVMm).ToList();
List<double> channelASVMmFirst = channelASVMm.FirstOrDefault();
EDIT: Once I have this information deserialized, how can I access the data I need? The only information I need to grab is the TransitTime and the Cost for each accessorial.
I'm working with an API in which I need data from nested objects, but I'm unsure of how to access this information. I've passed my data to the API and have set up new classes based on how the data comes back from the API.
Here's what the response looks like:
{"RatingResponse":
{"Success":"true",
"Message":"",
"QuoteID":"57450",
"LoadNum":"57450",
"Rates":{
"Rate":[
{"SCAC":"TEST",
"CarrierName":"TEST",
"TransitTime":"1",
"ServiceLevel":"D",
"TotalCost":"983.69",
"ThirdPartyCharge":"983.69",
"Accessorials":{
"Accessorial":[
{"Code":"400",
"Cost":"1,655.55",
"Description":"Freight"
},
{"Code":"DSC",
"Cost":"-985.55",
"Description":"Discount"
},
{"Code":"FUE",
"Cost":"313.69",
"Description":"Fuel Surcharge"
}
]
},
"QuoteNumber":""
},
{"SCAC":"TEST2",
"CarrierName":"TEST2",
"TransitTime":"1",
"ServiceLevel":"D",
"TotalCost":"983.69",
"ThirdPartyCharge":"983.69",
"Accessorials":{
"Accessorial":[
{"Code":"400",
"Cost":"1,655.55",
"Description":"Freight"
},
{"Code":"DSC",
"Cost":"-985.55",
"Description":"Discount"
},
{"Code":"FUE",
"Cost":"313.69",
"Description":"Fuel Surcharge"
}
]
},
"QuoteNumber":""
}
]
},
"AverageTotalCost":"983.69"
}
}
I've converted it to C#:
public class Accessorial
{
public string Code;
public string Cost;
public string Description;
}
public class Accessorials
{
public List<Accessorial> Accessorial;
}
public class Rate
{
public string SCAC;
public string CarrierName;
public string TransitTime;
public string ServiceLevel;
public string TotalCost;
public string ThirdPartyCharge;
public Accessorials Accessorials;
public string QuoteNumber;
}
public class Rates
{
public List<Rate> Rate;
}
public class RatingResponse
{
public string Success;
public string Message;
public string QuoteID;
public string LoadNum;
public Rates Rates;
public string AverageTotalCost;
}
public class Root
{
public RatingResponse RatingResponse;
}
The only values I need are the Rate Transit Time and Service Level as well as the Accessorial Costs. I'm a beginner with APIs and am not sure how to return only that information. Any help is greatly appreciated!
you don't need any classes if you use this code
var rate = (JArray)JObject.Parse(json)["RatingResponse"]["Rates"]["Rate"];
var result = rate.Select(r => new
{
TransitTime = (int)r["TransitTime"],
ServiceLevel = (string) r["ServiceLevel"],
AccessorialCost = ((JArray)r["Accessorials"]["Accessorial"]).Select(r => (double)r["Cost"]).ToList()
});
result (in json format)
[
{
"TransitTime": 1,
"ServiceLevel": "D",
"AccessorialCost": [
1655.55,
-985.55,
313.69
]
},
{
"TransitTime": 1,
"ServiceLevel": "D",
"AccessorialCost": [
1655.55,
-985.55,
313.69
]
}
]
or you can create a Data class instead of an anonymous
List<Data> result = rate.Select(r => new Data
{
....
}).ToList();
public class Data
{
public int TransitTime { get; set; }
public string ServiceLevel { get; set; }
public List<double> AccessorialCost { get; set; }
}
I like #Serge's answer but I prefer to have results in a class because "I only need..." never holds for very long, right? Here is a good discussion of loading the JSON into a complex object:
Your JSON erred in JSON2C#.com but essentially your root object needs the other classes. Something like
public class Root
{
public RatingResponse RatingResponse;
public Rates Rates;
public Accessorials Accessorials;
}
and then deserialize into your complex object
JsonConvert.DeserializeObject<RootObject>(json)
I'm doing this off the top of my head so forgive any syntax errors.
How to create model for this json? I can't understand how to add dictinary to this string array.
{
"ts": 1652718271,
"updates": [
[
4,
508976,
33,
466697301,
1551996353,
"Цацу",
{
"title": " ... ",
"type": "photo"
}
]
]
}
There are a few ways to handle JSON arrays of varied types. One way is to define a class with nullable fields of the types you may encounter in the array. For example,
public class Model
{
public int TS;
public Update[][] Updates;
}
public class Update
{
public int? Number;
public string Word;
public ModelDictionary Dictionary;
}
public class ModelDictionary
{
public string Title;
public string Type;
}
Then you could access each Update with something like
if (Number != null) { ... }
else if (Word != null) { ... }
else if (Dictionary != null) { ... }
Also, https://app.quicktype.io/ is always a great resource for generating C# models from JSON objects.
With this model you can deserialize using Newtonsoft.Json
class Serial
{
public string ts { get; set; }
public object [][] updates { get; set; }
}
I'm trying to use NewtonSoft.Json deserializer, but I don't know if what I'm trying to do is doable, cuase every example of collections that I've seen are like this:
public class ItemRecords
{
public List<ItemRecords> Items { get; set; }
...
}
And what I want is something that looks like as it's explained below...
I have this two classes:
public class ItemRecords : Collection<ItemRecord>
{
[JsonProperty("property1")]
public int Property1 { get; set; }
[JsonProperty("property2")]
public int Property2 { get; set; }
}
public class ItemRecord
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("item_prop1")]
public string ItemProp1 { get; set; }
...
}
I get this json back from my api:
{
property1: 25,
property2: 27,
item_record: [
{
id: 241,
item_prop1: "0.132",
item_prop2: "78787",
...
},
{
id: 242
item_prop1: "1212",
item_prop2: "3333",
...
}
...
]
}
ItemRecords is a collection of ItemRecord.
I tried by adding the JsonArray attribute to the ItemRecords class as follows:
[JsonArray(ItemConverterType = typeof(ItemRecord))]
public class ItemRecords : Collection<ItemRecord> { ... }
Here is the method that executes the request:
private static async Task<T> MakeRequest<T>(string urlRequest)
{
try
{
HttpWebRequest request = WebRequest.Create(urlRequest) as HttpWebRequest;
using (WebResponse response = await request.GetResponseAsync())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
string line = string.Empty;
StringBuilder sb = new StringBuilder();
while ((line = reader.ReadLine()) != null)
{
sb.Append(line);
}
T objectDeserialized = JsonConvert.DeserializeObject<T>(sb.ToString());
return objectDeserialized;
}
}
}
catch (Exception ex)
{
return default(T);
}
}
And call to this method looks like this:
...
return await MakeRequest<ItemRecords>(request);
I don't really know what else to do..
Any help would be appreciated.
Your basic difficulty is that the JSON standard has two types of container:
The object which is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Json.NET maps dictionaries and non-enumerable POCOS to objects by default, using reflection to map c# properties to JSON properties.
In the JSON you are getting back from your API, the outermost container is an object.
The array which is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma). Json.NET maps non-dictionary enumerables to arrays by default, serializing each collection item as an array entry.
In the JSON you are getting back from your API, the value of the item_record property is an array.
As a collection with properties, your ItemRecords cannot be mapped to either of these constructs automatically without losing data. Since Json.NET serializes collections as arrays by default, you will need to manually inform it that your type is to be serialized as an object by applying the [JsonObject] attribute. Then, introduce a synthetic item_record property to serialize and deserialize the collection items. Since you are inheriting from Collection<T>, you can use Collection<T>.Items for this purpose:
[JsonObject(MemberSerialization.OptIn)]
public class ItemRecords : Collection<ItemRecord>
{
[JsonProperty("property1")]
public int Property1 { get; set; }
[JsonProperty("property2")]
public int Property2 { get; set; }
[JsonProperty("item_record")]
IList<ItemRecord> ItemRecordList
{
get
{
return Items;
}
}
}
Using MemberSerialization.OptIn prevents base class properties such as Count from being serialized.
Sample fiddle.
As an aside, I don't particularly recommend this design, as it can cause problems with other serializers. For instance, XmlSerializer will never serialize collection properties; see here or here. See also Why not inherit from List?.
Simply add a List<ItemRecord> Records property to class ItemRecords:
public class ItemRecords
{
[JsonProperty("property1")]
public int Property1 { get; set; }
[JsonProperty("property2")]
public int Property2 { get; set; }
[JsonProperty("item_record")]
public List<ItemRecord> Records { get; set; }
}
This looks like you can have a dynamic number of results of properties and item properties like:
{
property1: 25,
property2: 27,
property3: 30,
item_record: [
{
id: 241,
item_prop1: "0.132",
item_prop2: "78787"
},
{
id: 242
item_prop1: "1212",
item_prop2: "3333",
item_prop3: "3333",
item_prop4: "3333",
}
] }
If this is the case, the best option in my opinion will be to change the structure to something like:
{
properties:[
25,
27,
30
],
itemRecords:[
{
id: 27,
itemProperties:[
"321",
"654",
"564"
]
},
{
id: 25,
itemProperties:[
"321",
"654"
]
},
]
}
Having trouble accessing a response back from a rest API service that has nested property.
For example here's the raw REST response:
"count": 5,
"results": [
{
"suggestion": "1 Wonston Road, Southampton, SO16 ...",
"matched": [[ 29, 37 ]],
{
"suggestion": "3 Wonston Road, Southampton, SO16 ...",
"matched": [[ 29, 37 ]],
Suggestion and Match are nested property within results.
The function that gets the response in my code is
IRestResponse<SearchResponse> response = client.Execute<SearchResponse>(request); I've used rest sharp here and the call is actually accurate as I get all the data back in form of a raw response.
I've defined the SearchResponse class as
//same for result, match, suggestion.
private string _count;
public string Count
{
get
{
return _count;
}
set
{
_count = value;
}
}
How can I define nested variables to pass them into SearchResponse.suggestion? Currently the nested properties are stored in results.
public class Result {
public string suggestion { get; set; }
public List<List<int>> matched { get; set; }
public string format { get; set; } }
public class RootObject {
public int count { get; set; }
public List<Result> results { get; set; } }
http://json2csharp.com Did the trick, Thank you