I want to access variables values from json list in C#.
my json String is as below
plase suggest me the way to access variable from json list .
example :-
{
"BillTransList": [
{
"aa": "13",
"ss": "200",
"LessItemList": [
{
"a": "13",
"b": "19"
},
{
"a": "17",
"b": "18"
}
]
},
{
"aa": "13",
"ss": "200",
"LessItemList": [
{
"a": "3",
"b": "9"
},
{
"a": "7",
"b": "8"
}
]
}
],
"aq": "2"
}
suggestions and corrections are welcome
thanks
You can create class to deserialize your JSON.
public class LessItemList
{
public string a { get; set; }
public string b { get; set; }
}
public class BillTransList
{
public string aa { get; set; }
public string ss { get; set; }
public List<LessItemList> LessItemList { get; set; }
}
public class RootObject
{
public List<BillTransList> BillTransList { get; set; }
public string aq { get; set; }
}
than you can deserialize using the below code
var jsonResponse = JsonConvert.DeserializeObject<RootObject>(result);
than you can access LessItemList simply by using LINQ.
Aliasgar Rajpiplawala's answer is Nice.
And I will do some supplement:
You should use some library to deserialize JSON string, such like Json.NET (Newtonsoft JSON).
And you can create your class using Json2Csharp (http://json2csharp.com/). Paste your json into it, and your class will be generated automic.
Related
I'm trying to deserialize a response from a firebase realtime database get/json, to get user locations that are online
example response:
{
"test1": {
"id": "test-1",
"location": {
"lat": 37.33097983,
"long": -122.03063943
}
},
"test2": {
"id": "test-2",
"location": {
"lat": 37.33021864,
"long": -122.02370753
}
},
"test3": {
"id": "test-3",
"location": {
"lat": 37.32873847,
"long": -122.01980584
}
},
"test4": {
"id": "test-4",
"location": {
"lat": 37.32563464,
"long": -122.01972943
}
},
"test5": {
"id": "test-5",
"location": {
"lat": 37.32472734,
"long": -122.02127163
}
}
}
I put this into a json to c# class converter and it creates a class for each user (Test1, Test2, Test3, etc). This would work, if the users from the example are the only users to be in the response. If I had a sixth user named "6test", I would need to also create a class for that one too.
How can I use the Json converter (Newtonsoft.Json or System.Text.Json) to return a user in a list<User>
you can use a dictionary in your case
using Newtosoft.Json;
Dictionary<string,Test> tests = JsonConvert.DeserializeObject<Dictionary<string,Test>>(json);
classes
public class Location
{
public double lat { get; set; }
public double #long { get; set; }
}
public class Test
{
public string id { get; set; }
public Location location { get; set; }
}
how to use
Test test5=tests["test5"];
or if you want to use list instead of Dictionary
var jsonParsed = JObject.Parse(json);
List<ListTest> list = jsonParsed.Properties().Select(p => new ListTest { Name = p.Name, Test = p.Value.ToObject<Test>() }).ToList();
how to use
Test test4 = list.Where(f=>f.Name=="test4").Select(t=>t.Test).FirstOrDefault();
class
public class ListTest
{
public string Name { get; set; }
public Test Test { get; set; }
}
I am trying to resolve the some complex JSON I am receiving to convert it to a C# Model so I can analyse and manipulate the data. I have tried converting the JSON by using JSON to C# but it doesn't work well when the name is dynamic. I want to focus on the Data.
The Item1 and SubItem1 etc are all variable strings so I can't hard code a model to pull them and the text is just a string within. The issue I am having is how to get the JSON into a usable format to access the Item1, SubItem1 and text values to manipulate their data.
I have looked into Dictionaries as suggested elsewhere but I am having no luck.
Model I have tried
public class Data
{
public string Status { get; set; }
public ResultInfo ResultInfo { get; set; }
public string Message { get; set; }
public Dictionary<string, SubData> Data {get;set;}
}
public class SubData
{
public Dictionary<string,List<string>> item {get;set;}
}
JSON
{
"Status": "OK",
"ResultInfo": {
"Prev": "PageUPURL",
"Next": "PageDownURL",
"total_count": "37",
"per_page": "3",
"page": "1"
},
"Message": "Ok.",
"Data": {
"Item1": [
{
"SubItem1": [
"Text"
]
}
],
"Item2": [
{
"SubItem2": [
"Text",
"Text",
"Text"
]
}
],
"Item3": [
{
"SubItem3": [
"Text"
]
},
{
"SubItem4": [
"Text"
]
}
]
}
}
Any suggestions, advice or help would be gratefully received.
For those task I use https://app.quicktype.io .
Because it can easly reconnize dictionary when the property name are numeric you just need to edit your Json a little.
And past it into the tool.
{
"Status": "OK",
"ResultInfo": {
"Prev": "PageUPURL",
"Next": "PageDownURL",
"total_count": "37",
"per_page": "3",
"page": "1"
},
"Message": "Ok.",
"Data": {
"1": [
{
"1": [
"Text"
]
}
],
"2": [
{
"1": [
"Text",
"Text",
"Text"
]
}
],
"3": [
{
"1": [
"Text"
]
},
{
"2": [
"Text"
]
}
]
}
}
The result class is :
public partial class Root
{
[JsonProperty("Status")]
public string Status { get; set; }
[JsonProperty("ResultInfo")]
public ResultInfo ResultInfo { get; set; }
[JsonProperty("Message")]
public string Message { get; set; }
[JsonProperty("Data")]
public Dictionary<string, List<Dictionary<string, List<string>>>> Data { get; set; }
}
public partial class ResultInfo
{
[JsonProperty("Prev")]
public string Prev { get; set; }
[JsonProperty("Next")]
public string Next { get; set; }
[JsonProperty("total_count")]
[JsonConverter(typeof(ParseStringConverter))]
public long TotalCount { get; set; }
[JsonProperty("per_page")]
[JsonConverter(typeof(ParseStringConverter))]
public long PerPage { get; set; }
[JsonProperty("page")]
[JsonConverter(typeof(ParseStringConverter))]
public long Page { get; set; }
}
Online Demo https://dotnetfiddle.net/1j42kR
nota bene: that tool also included a converter from "string" to "long" for "per_page": "3",
Change below line
public Dictionary<string, SubData> Data {get;set;}
as
public Dictionary<string, Dictionary<string, string[]>[]> Data { get; set; }
[
{
"id": "133",
"label": "S/M",
"price": "0",
"oldPrice": "0",
"products": [
"318",
"321",
"324",
"327"
]
},
{
"id": "132",
"label": "L/XL",
"price": "0",
"oldPrice": "0",
"products": [
"319",
"322",
"325",
"328"
]
},
{
"id": "131",
"label": "XXL/XXXL",
"price": "0",
"oldPrice": "0",
"products": [
"320",
"323",
"326",
"329"
]
}
]
I want to get 'label' where array "products" contains "321". How i can make this? I used library json.net
i make linq expression
JArray ja = JArray("this json");
JValue id = JValue.Parse("328");
ja.Select(x => x["label"]).Where(x => x["products"].Contains(id));
But i get "Cannot access child value on Newtonsoft.Json.Linq.JValue."
So you should define the class first:
class MyObj {
public string id { get; set; }
public string[] products { get; set; }
public string label { get; set; }
}
And deserialize that instead of object:
var deserialized = serializer.Deserialize<MyObj>(str);
var result = deserialized.Where(r => r.products.Contains("321")).ToList();
For this you can use any JSON library. e.g. JSON.NET
This LINQ to JSON sample
You need to use a library like JSON.NET.
In this case you can write something like this
string json = <your json string>;
var deserializedProduct = JsonConvert.DeserializeObject<List<Product>>(json).Where(p => p.products.Contains("321")).ToList();
where Product is
public class Product
{
public string id { get; set; }
public string[] products { get; set; }
public string label { get; set; }
}
I just got my json response as a string.My json is given below,
"code": 0,
"message": "success",
"students": {
"details":{
"hjeke": {
"id": "257633000000070001",
"name": "hjeke",
"percentage": 36,
"type": "Good",
},
"Second": {
"id": "257633000000073001",
"name": "Second",
"percentage": 4,
"type": "bad",
}
}
}
Like hjeke and Second there are many key value pairs,how can i deserialize my json using Newtonsoft.json
Try to understand my solution in your previous question
How to deserialize json data in windows phone?
Your first JSON in that question was good and simple to use.
JSON, where field names are unique not convinient to deserialize. So, you got problems such as public class Hjeke and public class Second for each instance, when you use code generator.
Use JSON-structure with list of students:
"code": 0,
"message": "success",
"students": [
{
"id": "257633000000070001",
"name": "hjeke",
"percentage": 36,
"type": "Good",
},
{
"id": "257633000000073001",
"name": "Second",
"percentage": 4,
"type": "bad",
}]
is good and flexible structure. Using this, you don't need to parse not obvious fields like
"details":{
"hjeke": {
and so on.
And work with them using classes, from my previous answer. The main idea - you need list of objects. public List<StudentDetails> students. Then, all students objects deserialized in List, which is easy to use.
As everybody mentioned your json seems to be very unflexible, huh.
You can extract the data you are interested in.
So this is your model:
public class StudentDetails
{
public string id { get; set; }
public string name { get; set; }
public int percentage { get; set; }
public string type { get; set; }
}
And this is how you can extract it:
var jsonObj = JObject.Parse(str);
// get JSON result objects into a list
var results = jsonObj["students"]["details"].Children().Values();
// serialize JSON results into .NET objects
var details = new List<StudentDetails>();
foreach (JToken result in results)
{
var st = result.ToString();
var searchResult = JsonConvert.DeserializeObject<StudentDetails>(st);
details.Add(searchResult);
}
I'm using a newtonsoft.json library here.
Your Response string has some mistakes man, its not a valid json
just small modification to be done as below:
{
"code": 0,
"message": "success",
"students": {
"details": {
"hjeke": {
"id": "257633000000070001",
"name": "hjeke",
"percentage": 36,
"type": "Good"
},
"Second": {
"id": "257633000000073001",
"name": "Second",
"percentage": 4,
"type": "bad"
}
}
}
}
you can make out the difference
Now Follow these steps:
1.Go to this link Json to C#
2.place your Json string there and generate C# class object
3.Now create this class in your solution
4.Now deserialize As below
var DeserialisedObject = JsonConvert.DeserializeObject<Your Class>(YourJsonString);
First, create the classes:
public class Hjeke
{
public string id { get; set; }
public string name { get; set; }
public int percentage { get; set; }
public string type { get; set; }
}
public class Second
{
public string id { get; set; }
public string name { get; set; }
public int percentage { get; set; }
public string type { get; set; }
}
public class Details
{
public List<Hjeke> hjeke { get; set; }
public List<Second> Second { get; set; }
}
public class Students
{
public List<Details> details { get; set; }
}
public class RootObject
{
public int code { get; set; }
public string message { get; set; }
public List<Students> students { get; set; }
}
After that, use JSON.NET to deserialize:
var deserialized = JsonConvert.DeserializeObject<Class1>(YourStringHere);
Do you have any influence over the json response? Details should probably be a JSONArray in this case, not an object with a varying amount of properties, since I assume that's what you mean is the issue here.
I have a json data when i'm trying to parse it returns error incorrect syntax please help me found the syntax error.
[{"isData":"Yes","Details":"[{"Id":"70","Name":"Test","FileName":"Uploaded","FileFormat":".mp4","FileType":"Video","FileDuration":"00:30:00 ","StartTime":"/Date(1372617000000)/","EndTime":"/Date(1372681771000)/","File":"2562013172331815635077778118152815.mp4"}]"}]
And this is the class that is used to serialize data, i am using javascript serializer
public enum Data
{
Yes,
No
}
public class MessageResponse()
{
public string isData { get; set; }
public string Details { get; set; }
}
List<MessageResponse> response = new List<MessageResponse>();
string strJson="[{"Id":"70","Name":"Test","FileName":"Uploaded","FileFormat":".mp4","FileType":"Video","FileDuration":"00:30:00 ","StartTime":"/Date(1372617000000)/","EndTime":"/Date(1372681771000)/","File":"2562013172331815635077778118152815.mp4"}]";
var newData = new MessageResponse
{
isData = Data.Yes.ToString(),
Details = strJson
};
response.Add(newData);
var jsonSerialiser1 = new JavaScriptSerializer();
string result = jsonSerialiser1.Serialize(response);
That's invalid JSON. The Details property is incorrectly formatted. You should remove the quotes around the value. It should be like this:
[
{
"isData": "Yes",
"Details": [
{
"Id": "70",
"Name": "Test",
"FileName": "Uploaded",
"FileFormat": ".mp4",
"FileType": "Video",
"FileDuration": "00:30:00 ",
"StartTime": "/Date(1372617000000)/",
"EndTime": "/Date(1372681771000)/",
"File": "2562013172331815635077778118152815.mp4"
}
]
}
]
or if you want Details to be a string property (representing JSON), which is kinda lame, you should properly escape the double quotes:
[
{
"isData": "Yes",
"Details": "[{\"Id\":\"70\",\"Name\":\"Test\",\"FileName\":\"Uploaded\",\"FileFormat\":\".mp4\",\"FileType\":\"Video\",\"FileDuration\":\"00: 30: 00\",\"StartTime\":\"/Date(1372617000000)/\",\"EndTime\":\"/Date(1372681771000)/\",\"File\":\"2562013172331815635077778118152815.mp4\"}]"
}
]
This structure you will be able to map to your current object model. But I would recommend you using the first approach.
Remove the " from the details data:
[{
"isData":"Yes",
"Details":
[{
"Id":"70",
"Name":"Test",
"FileName":"Uploaded",
"FileFormat":".mp4",
"FileType":"Video",
"FileDuration":"00:30:00",
"StartTime":"/Date(1372617000000)/",
"EndTime":"/Date(1372681771000)/",
"File":"2562013172331815635077778118152815.mp4"
}]
}]
Details should be of type class (i.e. user defined class) and it should hold all the properties.
public class Details
{ public int Id {get; set;} ... }
Firstly your json is invalid.
It should not have the " before and after the [ ]
[
{
"isData": "Yes",
"Details": [
{
"Id": "70",
"Name": "Test",
"FileName": "Uploaded",
"FileFormat": ".mp4",
"FileType": "Video",
"FileDuration": "00: 30: 00",
"StartTime": "/Date(1372617000000)/",
"EndTime": "/Date(1372681771000)/",
"File": "2562013172331815635077778118152815.mp4"
}
]
}
]
Secondly, your class could be improved to be:
public class MessageResponse
{
public string isData { get; set; }
public Details Details { get; set; }
}
public class Details
{
public int Id { get; set; }
public string Name { get; set; }
public string FileName { get; set; }
public string FileFormat { get; set; }
public string FileType { get; set; }
public string FileDuration { get; set; }
public string StartTime { get; set; }
public string EndTime { get; set; }
public string File { get; set; }
}
You would probably want to set up the correct data types though for things like Start Time etc...