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);
}
Related
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);
I am starting c# and I was asked to create a small Api using a given Json file as DB.
My json file looks like:
{"Items": [
{
"id": 1,
"name": "Apple",
"price": 12.50,
"image": "some url",
"description": "Some text",
"tags": [ "fruit", "red" ],
"category": "fruit"
},
]}
I created a model:
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Image { get; set; }
public string Description { get; set; }
public List<Tags> Tags { get; set; }
public string Category { get; set; }
}
public class Tags
{
public string Tag { get; set; }
}
And my controller looks like:
[ApiController]
[Route("api/[controller]")]
public class ProductController : Controller
{
[HttpGet]
public IEnumerable<Product> Get()
{
StreamReader r = new StreamReader("./items.json");
string jsonString = r.ReadToEnd();
List<Product> productsList = JsonConvert.DeserializeObject<List<Product>>(jsonString);
return productsList;
}
}
The error I get:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Kata.Product]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
As I am new to c#, I am having trouble to find out how to simply return what I have in my Json file. At some point I was able to return the list by changing the json file(not the greatest idea) but all the items were null.
Thank you
You have a bug in your json classes. You can't use a special class for the tags, try to replace it by string array or list. The same about items. You deserialized the whole Root object, items just a property of this object. So since you don't need the whole object but just list of items, you have to select only them.
var jsonDeserialized= JsonConvert.DeserializeObject<Root> (jsonString);
List<Product> productsList = jsonDeserialized.Items ;
classes
public class Product
{
public int id { get; set; }
public string name { get; set; }
public double price { get; set; }
public string image { get; set; }
public string description { get; set; }
public List<string> tags { get; set; }
public string category { get; set; }
}
public class Root
{
public List<Product> Items { get; set; }
}
and fix json
{
"Items": [{
"id": 1,
"name": "Apple",
"price": 12.50,
"image": "some url",
"description": "Some text",
"tags": ["fruit", "red"],
"category": "fruit"
}]
}
I am deserializing some JSON into a list of the type Data1.
The class:
public class RootObject
{
public List<Data1> data { get; set; }
public string status { get; set; }
public int requested { get; set; }
public int performed { get; set; }
}
public class Data1
{
public List<ClioFolder> data { get; set; }
public int status { get; set; }
}
public class ClioFolder
{
public int id { get; set; }
public string name { get; set; }
public Parent parent { get; set; }
}
public class Parent
{
public int id { get; set; }
public string name { get; set; }
}
The Json:
{
"data": [
{
"data": [
{
"id": 66880231,
"name": "root",
"parent": null
},
{
"id": 68102146,
"name": "Dummy",
"parent": {
"id": 66880231,
"name": "root"
}
}
],
"status": 200
}
],
"status": "completed",
"requested": 10,
"performed": 10
}
Using this command:
List<Data1> allData = JsonConvert.DeserializeObject<RootObject>(content).data;
This is working fine, but what I really need is the data from within the two "data" objects in it's own list too. I thought I would be able to do something like:
List<ClioFolder> allClios = allData.data;
But this doesn't work. I did also try deserailizing from the JSON directly into this second list, but this doesn't work either:
List<Cliofolder> allClios = JsonConvert.DeserializeObject<RootObject>(content).data.data;
What would be the correct way to achieve this?
It's a list. your should use:
List<ClioFolder> test = allData.FirstOrDefault()?.data;
tried to make a clean example. and im pretty sure this can be achieved with linq but i can't think of how to flatten a multidimensional array in linq right now.
List<ClioFolder> allClios = new List<ClioFolder>();
foreach(Data1 data in allData)
{
allClios.AddRange(data.data.ToArray());
}
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());
}