I have been working trying to import a list of objects from Json to C#.
The Json structure is:
"meta": {
"file_version": 11,
"machine_number": 210xxxxx,
"software": {
"software_date": "",
"software_version": ""
},
"saved": {
"user": "Bxxxxxx",
"date": "20220810",
"time": "132156"
},
"application": {
"name": "Support",
"type": "xxxxx_Support"
},
"validity": {
"machine_model": "xxx",
"arm_assembly": "xxx",
"boom_pedestal": "xxx"
}
},
"data": {
"data532": {
"number": 54,
"name": "Abstützung vorne - zulässige vertikale Beinkraft (P1.Q1)",
"format": 0,
"digit": 0,
"unit": 10,
"category": 0,
"min": 0,
"max": 1000000,
"value": 225000,
"hexvalue": "0x00036EE8",
"binvalue": "0b00000000000000110110111011101000"
},
"data533": {
"number": 55,
"name": "Abstützung vorne - zulässige vertikale Beinkraft (P1.Q2)",
"format": 0,
"digit": 0,
"unit": 10,
"category": 0,
"min": 0,
"max": 1000000,
"value": 0,
"hexvalue": "0x00000000",
"binvalue": "0b00000000000000000000000000000000"
.
.
.
.
.
My problem is that I need to set up the objects DataXXX in C#.
Im trying with:
var dataconfig = JsonConvert.DeserializeObject<Data>(jsonfile);
Where class Data is
public class Data
{
public int number { get; set; }
public string name { get; set; }
public int format { get; set; }
public int digit { get; set; }
public int unit { get; set; }
public int category { get; set; }
public int min { get; set; }
public int max { get; set; }
public int value { get; set; }
public string hexvalue { get; set; }
public string binvalue { get; set; }
}
But my dataXXX is inside another object called Data so the code is not working. And it's not a list also.
In Newtonsoft.Json, there are two API's, one high-level (JsonConvert) and one low-level (Linq-to-Json). JsonConvert is great for parsing if the data matches the C# class structures you have. Linq-to-Json is great for custom processing and flexibility.
In your case, since your property names have numbers in them that you need to standardize to match C# classes, you probably need to use Linq-to-Json. This parses JSON into objects similar to a Dictionary. Here are the intro docs.
If you need only a data part, you can parse the json at first, after this you can deserialize any part
var jsonParsed = JObject.Parse(jsonFile);
Dictionary<string,Data> dataconfig = jsonParsed["data"].ToObject<Dictionary<string,Data>>();
you should use Dictionary
public class Data {
public Dictionary<string,DataModel> data {get; set;}
}
public class DataModel {
public int number { get; set; }
public string name { get; set; }
public int format { get; set; }
public int digit { get; set; }
public int unit { get; set; }
public int category { get; set; }
public int min { get; set; }
public int max { get; set; }
public int value { get; set; }
public string hexvalue { get; set; }
public string binvalue { get; set; }
}
with Newtonsoft:
JsonConvert.DeserializeObject<Data>(jsonfile); //jsonfile must be includes data.
with System.Text.Json
JsonSerializer.Deserialize<Data>(jsonfile);
Related
I am using an API for car HP and PCP details. When API returns the response object it has some dynamic object and objects names depending upon the parameters given during JSON call input parameters. Please tell me how can I convert / deserialize this response object into C# object. I tried JSON convert to C# classes but didn't get required results. Given below in API response object. I need to parse this result object into C# object so i can use it for displaying required values on front end.
JSON Response / Result Object
{
"success": true,
"data": {
"hp": {
"58995": {
"48": {
"40": {
"9000": [
{
"balance": 58955,
"first": 1403.62,
"regular": 1403.62,
"final": 1413.62,
"total": 67423.76,
"charges": 8428.76,
"apr": 6.92,
"apr_nofees": 6.91,
"term": 48,
"flat": 3.57,
"fee_front": "0.00",
"fee_back": "10.00",
"fee_spread": 0,
"ref": "1000.00",
"ho": 0,
"ho_a": 0,
"sb": 0,
"id": "12",
"product_name": "HP/ML No Fees",
"excess_mileage": false
}
]
}
}
}
},
"pcp": {
"58995": {
"48": {
"40": {
"9000": [
{
"balance": 58955,
"first": 1251.04,
"regular": 1251.04,
"final": 8386,
"total": 68475.92,
"charges": 9480.92,
"apr": 6.89,
"apr_nofees": 6.89,
"rv": 8385,
"term": 48,
"flat": 3.56,
"rv_interest": 1084.68,
"charges_ex_rv": 8396.24,
"fee_front": "0.00",
"fee_back": "1.00",
"fee_spread": 0,
"ref": 0,
"ho": 0,
"ho_a": 0,
"sb": 0,
"id": "25",
"product_name": "BNP PCP",
"excess_mileage": "7p"
}
]
}
}
}
},
"count": 2,
"taken": 443
}
}
try this
var jsonParsed = JObject.Parse(json);
var count = (int)jsonParsed["data"]["count"];
var taken = (int)jsonParsed["data"]["taken"];
((JObject)jsonParsed["data"]).Descendants()
.OfType<JProperty>()
.Where(attr => attr.Name == "count" || attr.Name == "taken")
.ToList()
.ForEach(attr => attr.Remove());
Data data = jsonParsed.ToObject<Data>();
data.count = count;
data.taken = taken;
classes
public class Data
{
public bool success { get; set; }
public Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, Product[]>>>>> data { get; set; }
public int count { get; set; }
public int taken { get; set; }
public class Product
{
public int balance { get; set; }
public double first { get; set; }
public double regular { get; set; }
public double final { get; set; }
public double total { get; set; }
public double charges { get; set; }
public double apr { get; set; }
public double apr_nofees { get; set; }
public int term { get; set; }
public double flat { get; set; }
public string fee_front { get; set; }
public string fee_back { get; set; }
public int fee_spread { get; set; }
[JsonProperty("ref")]
public string refer { get; set; }
public int ho { get; set; }
public int ho_a { get; set; }
public int sb { get; set; }
public string id { get; set; }
public string product_name { get; set; }
public object excess_mileage { get; set; }
}
I am reading a json-string from an API (in a script component i SSIS). The json looks something like the one below (this is only one record, the real string contains many more). When trying to deserialize into a class containing the needed properties, I would like to put the "value" for the "costCenters"-property into a string property in my table. How ever, since the costCenters-value in itself contains a JSON, the deserialization fails (because it encounters the objects inside it).
If I exclude the property CostCenters from my class, it manages to deserialize the other properties just fine. I would think (hope) that it would be possible to force the inner JSON into a string property? Any suggestions?
This is my class that is used for the deserilazing:
internal class Unit
{
public int ParentId { get; set; }
public int CompanyId { get; set; }
public string Abbreviation { get; set; }
public string AbbreviationPath { get; set; }
public int Manager { get; set; }
public int UnitId { get; set; }
public string Name { get; set; }
public string LevelDescription { get; set; }
public int OrfuCompanyId { get; set; }
public string Resh { get; set; }
//If the below propery is commented out, the deserializing works fine.
public string CostCenters { get; set; }
public int Level { get; set; }
public int OrfuUnitId { get; set; }
}
This is how I call the deserializer for NewtonSoft:
var units = new List<Unit>();
units = JsonConvert.DeserializeObject<List<Unit>>(jsonString);
This is how the jsonString looks (edited):
[
{
"$id": "1",
"parentId": 999,
"companyId": 9123,
"abbreviation": "ZZZ",
"abbreviationPath": "SOMEPATH",
"costCenters": [
{
"$id": "12",
"costCenter": "12345",
"costCenterSourceId": "99",
"costCenterSource": "TBF",
"costCenterTypeId": "999",
"costCenterType": "TypeOfCostCenter",
"startDate": "2018-01-01T00:00:00",
"endDate": "9999-12-31T00:00:00"
},
{
"$id": "88",
"costCenter": "191945444",
"costCenterSourceId": "88",
"costCenterSource": "TBB",
"costCenterTypeId": "15",
"costCenterType": "SomeTextHere",
"startDate": null,
"endDate": null
}
],
"manager": 12345678,
"deputy": 0,
"homeShare": "\\\\someaddress.net\\someFolder\\SomeCode",
"objectGuid": "ThisIsAGUID",
"distinguishedName": "OU=ABC,OU=NNN,OU=FFF,OU=HHH,OU=HNV,OU=IDK,DC=heipaadeg,DC=com",
"orfuUnitId": 9125,
"orfuCompanyId": 9123,
"resh": "123456789",
"nis": "",
"unitId": 4321,
"name": "2 some name",
"level": 9,
"levelDescription": "Level number 4"
}
]
One workaround is to add a field to Unit called CostCentersString in which the CostCenters list is re-serialized:
In Unit class definition:
...
public List<dynamic> CostCenters { get; set; }
public String CostCentersString { get; set; }
Then use:
List<Unit> units = JsonConvert.DeserializeObject<List<Unit>>(jsonString);
foreach (Unit u in units)
{
u.CostCentersString = JsonConvert.SerializeObject(u.CostCenters);
}
I'm attempting to parse a rather convoluted/unnecessarily complicated JSON output using newtonsoft in C# however for some reason my parser always returns null. I have searched all over SO and cant't seem to find a solution.
An example of a JSON file I'm trying to parse:
{
"success": 1,
"d": {
"gameData": {
"MJ2Y7tDg": {
"scores": [
{
"max": 1.83,
"avg": 1.73,
"rest": 2,
"active": true,
"scoreid": "2c556xv464x0x4vtqc"
},
{
"max": 3.47,
"avg": 3.24,
"rest": 2,
"active": true,
"scoreid": "2c556xv498x0x0"
},
{
"max": 6.06,
"avg": 5.08,
"rest": 1,
"active": true,
"scoreid": "2c556xv464x0x4vtqd"
}
],
"count": 62,
"highlight": [
false,
true
]
},
"jZICYUQu": {
"scores": [
{
"max": 2.25,
"avg": 2.13,
"rest": null,
"active": true,
"scoreid": "2c5guxv464x0x4vuiv"
},
{
"max": 3.55,
"avg": 3.29,
"rest": null,
"active": true,
"scoreid": "2c5guxv498x0x0"
},
{
"max": 3.9,
"avg": 3.33,
"rest": null,
"active": true,
"scoreid": "2c5guxv464x0x4vuj0"
}
],
"count": 62,
"highlight": [
false,
false
]
}
}
}
}
This is what i have so far, I am very new to JSON wrangling :)
public class RootObject
{
public int success { get; set; }
public List<d> d { get; set; }
}
public class d
{
public List<gameData> gameData { get; set; }
}
public class gameData
{
public IDictionary<string, Score> gameData{ get; set; }
public List<scores[]> GameList;
}
public class Score
{
public double max { get; set; }
public double avg { get; set; }
public int rest { get; set; }
public bool active { get; set; }
public string scoreid { get; set; }
}
Anyone with more JSON wrangling experience know how to get this working?
Thankyou in advanced.
P.S I am currently in high school, learning C#
The parser returns null because structure of your classes doesn't correctly resemble the structure of JSON. The correct structure of classes would be:
public class RootObject
{
public int success { get; set; }
public Class_d d { get; set; }
}
public class Class_d
{
public Dictionary<string, GameData> gameData { get; set; }
}
public class GameData
{
public List<Score> scores { get; set; }
public int count { get; set; }
public bool[] highlight { get; set; }
}
public class Score
{
public decimal max { get; set; }
public decimal avg { get; set; }
public int? rest { get; set; }
public bool active { get; set; }
public string scoreid { get; set; }
}
and you can use it as follows:
string json = "..."; // the JSON in your example
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
I was wondering how I could at best deserialize this json string. For doing that I am using Newtonsoft.json as a plugin with Xamarin.
I only need the parts that says "transaction" and the array in it "transactions" in a list.
{
"id": 999,
"transactions": [
{
"order": 1,
"displayName": "01_lgn",
"transaction": {
"id": 7791,
"name": "01_lgn",
"description": null,
"warning": 1,
"poor": 2,
"timeOut": 45,
"tolerated": 3,
"frustrated": 7,
"state": 1,
"includeInThroughputCalculation": true
}
}
{
"order": 2,
"displayName": "02",
"transaction": {
"id": 7793,
"name": "02",
"description": null,
"warning": 1,
"poor": 2,
"timeOut": 45,
"tolerated": 3,
"frustrated": 7,
"state": 1,
"includeInThroughputCalculation": true
}
}
],
"defies": null,
"state": 1,
"reportDisplayName": "testSomething"
}
What I already have tried is to put it in a strongly typed class and then make a list of it.
public class testTransaction
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("state")]
public int State { get; set; }
[JsonProperty("reportDisplayName")]
public string ReportDisplayName { get; set; }
[JsonProperty("transactions")]
public List<testTransactions> testTransactions { get; set; }
}
public class testTransactions
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("description")]
public object Description { get; set; }
[JsonProperty("warning")]
public int Warning { get; set; }
[JsonProperty("poor")]
public int Poor { get; set; }
[JsonProperty("timeOut")]
public int TimeOut { get; set; }
[JsonProperty("tolerated")]
public int Tolerated { get; set; }
[JsonProperty("frustrated")]
public int Frustrated { get; set; }
[JsonProperty("state")]
public int State { get; set; }
[JsonProperty("includeInThroughputCalculation")]
public bool IncludeInThroughputCalculation { get; set; }
}
But when I try to deserialize it in this way the "searchResult" is empty and I see that nothing is added to the list.
var bleh = jsonstring;
JObject parsedketenObject = JObject.Parse(bleh);
IList<JToken> jTokenResults1 = parsedketenObject;
IList<JToken> jTokenResults2 = parsedketenObject ["transactions"].Children ().ToList ();
IList<JToken> jTokenResults3 = parsedketenObject["transactions"][0]["transaction"].Children().ToList();
_Transactions_list = new List<testTransaction>();
foreach (JToken result in jTokenResults2)
{
testTransaction searchResult = JsonConvert.DeserializeObject<testTransaction>(result.ToString());
_Transactions_list.Add(searchResult);
}
Firstly, the JSON seems to be malformed, you are missing comma.
{
"id": 999,
"transactions": [
{
"order": 1,
"displayName": "01_lgn",
"transaction": {
"id": 7791,
"name": "01_lgn",
"description": null,
"warning": 1,
"poor": 2,
"timeOut": 45,
"tolerated": 3,
"frustrated": 7,
"state": 1,
"includeInThroughputCalculation": true
}
}, <-------- HERE
{
"order": 2,
"displayName": "02",
"transaction": {
"id": 7793,
"name": "02",
"description": null,
"warning": 1,
"poor": 2,
"timeOut": 45,
"tolerated": 3,
"frustrated": 7,
"state": 1,
"includeInThroughputCalculation": true
}
}
],
"defies": null,
"state": 1,
"reportDisplayName": "testSomething"
}
Additionally, try these for your POCO instead:
public class TransactionDetails
{
public int id { get; set; }
public string name { get; set; }
public object description { get; set; }
public int warning { get; set; }
public int poor { get; set; }
public int timeOut { get; set; }
public int tolerated { get; set; }
public int frustrated { get; set; }
public int state { get; set; }
public bool includeInThroughputCalculation { get; set; }
}
public class Transaction
{
public int order { get; set; }
public string displayName { get; set; }
public TransactionDetails transaction { get; set; }
}
public class RootObject
{
public int id { get; set; }
public List<Transaction> transactions { get; set; }
public object defies { get; set; }
public int state { get; set; }
public string reportDisplayName { get; set; }
}
Then you can use
var x = JsonConvert.DeserializeObject<RootObject>(blah);
x will contain transactions, which is already a list.
This method is not strongly typed, but it will work:
var jsonString = GetTheJson(); // however you get your json
dynamic jsonObject = JsonConvert.DeserializeObject(jsonString);
foreach (var txn in jsonObject.transactions)
{
Console.WriteLine("{0} {1} {2}", txn.order, txn.displayName, txn.transaction.id);
}
The best way to serialize/deserialize a json string to json object is using Google Gson library. You should create DTO files and use its type to serialize the string.
The documentation can be found here: https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html
In windows Phone application i know how to display images forma json data..
Regarding that i followed many articles on parsing the json data..
on the every article they have images in this way
"images" : "http://thegraphicsfairy.com/wp-content/uploads/2013/03/Stock-Image-Bird-Branch-GraphicsFairy1.jpg"
But i have Json Data like
"images" : [
"http://thegraphicsfairy.com/wp-content/uploads/2013/03/Stock-Image-Bird-Branch-GraphicsFairy1.jpg"
]
like that i have many images in my JSON data
"flick" : ["http://thegraphicsfairy.com/wp-content/uploads/2013/05/House-Painter-Man-Image-GraphicsFairy1.jpg"
]
"title" : ["http://scm-l3.technorati.com/11/11/17/56749/google-docs-revision.jpg%3Ft%3D20111117074048"
]
So am unable to Parse them i tried with {get,set}
and i followed many articles like
1. Facebook graph.
2. Facebook Feed.
3. Josn list box
4. Nokia Flicker
I want to display them in a Async List Box view
and one more thing i stopped at starting Because in every json data it starts with a JSON Object,.. But MY json data srats with JSON Array inside JSON OBJecet.. aganin Repeat...
This is my JSON data.. and i am getting this data from a server so i may not change the Server
{
"rC": "success",
"SpData": {
"results": [
{
"ndetails": [
{
"laoffers": [],
"offers_count": 0,
"sku": "3246",
"url": "http://www.google.com"
},
{
"laoffers": [
{
"id": "0c4ggUUkY8",
"price": "313.56",
"currency": "USD"
},
{
"id": "5OhvKwkQ",
"price": "311.95",
"currency": "USD"
}
],
"offers_count": 2,
"name": "abc.com",
"url": "http://www.bing.com"
},
{
"laoffers": [
{
"id": "0bZw4cCK",
"price": "339.99",
"currency": "USD"
},
{
"id": "CwEEA",
"shipping": "8.17",
"price": "299.99",
"currency": "USD"
}
],
"o_count": 2,
"name": "aaaa.com",
"recentoffers_count": 1,
"sku": "8567757",
"url": "http://www.avcd.com"
}
],
"model": "818BLK",
"weight": "394625.36",
"price_currency": "USD",
"gtins": [
"044558"
],
"cat_id": "23042",
"features": {
"Condition": "New",
"RAM - Memory": "2 GB - DDR3L SDRAM",
"Rear-facing Camera - Camera": "5 Megapixel"
},
"length": "215.90",
"created_at": 132657,
"variation_id": "2SKEFyM",
"geo": [
"usa"
],
"width": "130.05",
"upc": "84884848",
"ean": "47444",
"category": "Tablets",
"price": "334.99",
"updated_at": 1391388552,
"color": "Black",
"manufacturer": "abc ,amifracture",
"images_total": 1,
"images": [
"http://2.bp.blogspot.com/-AwTiVBnB_e4/T7-Wf4Z9HqI/AAAAAAAAACA/DA2UuBQsQ9g/s1600/funny-animal-pic-images-photos-02.jpg"
],
"brand": "ccc",
"sem3_id": "0iVcESQOy",
"offers_total": 169
}
],
"total_results_count": 1,
"results_count": 1,
"code": "OK",
"offset": 0
}
}
While Parsing at starting i failed Because.. in graph.facebook.com
thy have only two Json arrays..
But i have Json array Inside the Json object or JOSN object inside the json arrya..
and all the images are inside the json array which is inside the results which is inside a empty json object, and that is inside a JSOn array..
i am unable to parse some fields at starting.. and images are inside the json array are not displaying...
So i want to Parse JSON plus images By any json parsing methoid in C#(windows phone)..
and i want to deserilize the data including Images..
like this for example..
private void jsonButton_Click(object sender, RoutedEventArgs e)
{
string fbURL = "http://graph.facebook.com/microsoft";
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += (sndr, eArgs) =>
{
if (!string.IsNullOrEmpty(eArgs.Result))
{
var json = JsonConvert.DeserializeObject<MyPageObject>(eArgs.Result);
this.jAbout.Text = json.about;
this.jCategory.Text = json.category_list[0].name;
this.jFounded.Text = json.founded;
this.jWebsite.Content = json.website;
this.jWebsite.NavigateUri = new Uri(json.website, UriKind.Absolute);
this.jAddress.Text = json.location.street + ", " + json.location.city + ", " + json.location.state;
this.jLikes.Text = json.likes.ToString();
// download cover image
string imageSource = json.cover.source;
this.CoverImage.Source = new BitmapImage(new Uri(imageSource, UriKind.Absolute));
}
};
webClient.DownloadStringAsync(new Uri(fbURL, UriKind.Absolute));
}
At here they have image as normal way.. But i have image inside a JSON array..
and They used Root Object at starting Because they have only one Main JSON arrya.. But i have a many Json arrays and Objects which means [{ or { some data [{ some data... Like that i have..
And at here i want the out put exact like Nokia flicker.... But over there They parsed XML json data.. But i want ONly for JSON data..
Here is a link that convert a json string to respective c# class architecture. Below is the class architecture of your json string.
public class Ndetail
{
public List<object> laoffers { get; set; }
public int offers_count { get; set; }
public string sku { get; set; }
public string url { get; set; }
public string name { get; set; }
public int? o_count { get; set; }
public int? recentoffers_count { get; set; }
}
public class Features
{
public string Condition { get; set; }
public string __invalid_name__RAM - Memory { get; set; }
public string __invalid_name__Rear-facing Camera - Camera { get; set; }
}
public class Result
{
public List<Ndetail> ndetails { get; set; }
public string model { get; set; }
public string weight { get; set; }
public string price_currency { get; set; }
public List<string> gtins { get; set; }
public string cat_id { get; set; }
public Features features { get; set; }
public string length { get; set; }
public int created_at { get; set; }
public string variation_id { get; set; }
public List<string> geo { get; set; }
public string width { get; set; }
public string upc { get; set; }
public string ean { get; set; }
public string category { get; set; }
public string price { get; set; }
public int updated_at { get; set; }
public string color { get; set; }
public string manufacturer { get; set; }
public int images_total { get; set; }
public List<string> images { get; set; }
public string brand { get; set; }
public string sem3_id { get; set; }
public int offers_total { get; set; }
}
public class SpData
{
public List<Result> results { get; set; }
public int total_results_count { get; set; }
public int results_count { get; set; }
public string code { get; set; }
public int offset { get; set; }
}
public class RootObject
{
public string rC { get; set; }
public SpData SpData { get; set; }
}
DataContractJsonSerializer useful with this class architecture to parse a json string.
Below is the sample code.
// json parsing code.
MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(Your json string));
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(RootObject));
RootObject parsedData= dataContractJsonSerializer.ReadObject(memoryStream) as RootObject;
if(parsedData!=null)
{
MessageBox.Show(parsedData.SpData.results.First().ndetails.First().url.ToString());
}