This question already has an answer here:
Deserializing JSON into an object
(1 answer)
Closed 5 years ago.
I have the following string of Json records:
{
"records":[
{
"PK":"1_1_8",
"ID":"8",
"DeviceID":"1",
"RootID":"1",
"CustName":"test1",
"CustSurname":"test2",
"Address":"Nisou 1",
"City":"",
"ZipCode":"",
"PhoneNumber":"45646",
"HomePhoneNumber":"",
"Email":"",
"Notes":"",
"Owner":"1",
"LanguageID":"1",
"LanguagePK":"",
"DeletedFlag":"false",
"created":"2017-10-25 10:15:00",
"modified":"2017-10-25 09:35:43"
},
{
"PK":"1_1_33",
"ID":"33",
"DeviceID":"1",
"RootID":"1",
"CustName":"",
"CustSurname":"",
"Address":"",
"City":"",
"ZipCode":"",
"PhoneNumber":"",
"HomePhoneNumber":"",
"Email":"",
"Notes":"",
"Owner":null,
"LanguageID":"0",
"LanguagePK":"",
"DeletedFlag":"true",
"created":"2017-10-25 10:13:54",
"modified":"2017-10-25 10:13:54"
},
{
"PK":"1_1_16",
"ID":"16",
"DeviceID":"1",
"RootID":"1",
"CustName":"Theodosis",
"CustSurname":"",
"Address":"Dali",
"City":"Nicosia",
"ZipCode":"2540",
"PhoneNumber":"45645",
"HomePhoneNumber":"99123456",
"Email":"theodosis#gmail.com",
"Notes":"",
"Owner":"",
"LanguageID":"1",
"LanguagePK":"",
"DeletedFlag":"false",
"created":"2017-10-25 09:36:22",
"modified":"2017-10-25 09:36:22"
}
]
}
I am using Xamarin PCL in C# trying to parse this string into a list of objects.
I have a Customer class:
public class Customer
{
[PrimaryKey]
public string PK { get; set; }
public int DeviceID { get; set; }
public int ID { get; set; }
public string RootID{ get; set; }
public string CustName { get; set; }
public string CustSurname { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string ZipCode { get; set; }
public string PhoneNumber { get; set; }
public string HomePhoneNumber { get; set; }
public string Email { get; set; }
public string Notes { get; set; }
public bool Owner { get; set; }
public int LanguageID { get; set; }
public string LanguagePK { get; set; }
public bool DeletedFlag { get; set; }
public DateTime created { get; set; }
public DateTime modified { get; set; }
}
I also tried out having a container class with a list of Customer objects.
public class DataContainer
{
public List<Customer> customers { get; set; }
}
I have seen quite a few of examples online on how to parse this into a list or any workable type but nothing seems to be working for me.
I have tried the following (JsonResults holds the string of Json records):
var observation = JsonConvert.DeserializeObject<DataContainer>(JsonResults);
From other posts, I am not able to access JavaScriptSerializer class from my code, perhaps because of the Xamarin PCL Framework I am using.
Any ideas would be very welcome, as I said I do not mind the format I parse the string into, as long as it's workable.
Thank you.
You would have to make the following changes to your code to make this work.
First and most importantly, you don't have a property customers, you have records, so either rename it
public class DataContainer {
public List<Customer> records { get; set; }
}
or add a JsonProperty attribute
[JsonProperty(PropertyName = "records")]
Secondly, your Owner is a bool in C# and a nullable int (int?) in Json. So either change it in your C# class
public int? Owner { get; set; }
or write a converter to do that (e.g. like here)
[JsonConverter(typeof(NullableIntToBooleanConverter))]
public bool Owner { get; set; }
Here is a working .NetFiddle
The JSON string you provided is a JSON object, which contains a single property called records. records property is a List<Customer>. You can not deserialize the given string directly into DataContainer class that you provided because the property names do not match.
In the Class that your provided it is called customers
public class DataContainer {
public List<Customer> customers { get; set; } //records
}
Or please have a look at the attribute for a bit of advanced mapping
[JsonProperty]
JSON you provided is of the form:
{"records":[{Customer},{Customer},{Customer}]}
But Owner property is "1", null or "". Therefore I would suggest redefining Owner as int? (nullable)
Your string shows one object with a property named records that contains a list of other objects. Your code is trying to deserialize this into an object that doesn't have such a property.
Furthermore, the string contains objects with a property Owner that may be missing or have a numeric value. It's definitely not a bool.
You'll have to change Owner to :
public int? Owner { get; set; }
To deserialize the string, you need an object with a records property:
public class DataContainer
{
public Customer[] records { get; set; }
}
var data=JsonConvert.DeserializeObject<DataContainer>(json);
Debug.Assert(data.records.Length == 3);
I'm currently working on a project where I make a request to the Riot Games API, parse the JSON, and do some stuff with it. I have the request working, and I know I'm getting valid JSON. My issue is using JSON.Net to deserialize the JSON.
The JSON is of the following structure:
{
"xarcies": {
"id": 31933985,
"name": "Farces",
"profileIconId": 588,
"revisionDate": 1450249383000,
"summonerLevel": 30
}
}
I want to load this data into the following class
[JsonObject(MemberSerialization.OptIn)]
class Summoner
{
[JsonProperty("id")]
public long id {get;set;}
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("profileIconId")]
public int profileIconId { get; set; }
[JsonProperty("revisionDate")]
public long revisionDate { get; set; }
[JsonProperty("summonerLevel")]
public long summonerLevel { get; set; }
}
The issue I'm having is that because I'm given a "xarcies" object that contains the information I need, I'm not sure how to go about designing a class that can accept the JSON data. I've seen some examples that use a RootObject class to take the object and that class has a subclass that all the pairs are put into, but I can't seem to get it to work. Every time I run it the attributes for the object end up being NULL.
You can deserialize your JSON as a Dictionary<string, Summoner>:
var root = JsonConvert.DeserializeObject<Dictionary<string, Summoner>>(jsonString);
The dictionary will be keyed by the user name, in this case "xarcies". See Deserialize a Dictionary.
I just used json2csharp to create the following class (its types look a bit different then yours):
public class UserData
{
public int id { get; set; }
public string name { get; set; }
public int profileIconId { get; set; }
public long revisionDate { get; set; }
public int summonerLevel { get; set; }
}
public class RootObject
{
public KeyValuePair<string, UserData> value { get; set; }
}
I'm using the Newtonsoft Json (http://james.newtonking.com/json) library to deserialize some json into an object but having some trouble with a boolean value. Please see my example below. The example should run in LinqPad as long as you reference the Newtonsoft dll (I'm using the latest at the moment which has a file version of 6.0.3.17227). The issue is deserializing into the UpdateLocationsRequest object.
Any help is appreciated.
void Main()
{
string json1 = "{\"token\":\"5b2a38c8-c211-481e-aa75-7d52fff6eb2f\",\"share\":true}";
string json2 = "{\"token\":\"5b2a38c8-c211-481e-aa75-7d52fff6eb2f\",\"locationList\":[{\"desc\":\"This is a test\",\"name\":\"Andrew 3\",\"deviceLocationId\":\"a8d2bfae-4493-41cd-ae1e-ea0da66da0cf\",\"locType\":1,\"lon\":-80.27543,\"lat\":43.42618,\"share\":true}]}";
TestClass req1 = JsonConvert.DeserializeObject<TestClass>(json1);
UpdateLocationsRequest req2 = JsonConvert.DeserializeObject<UpdateLocationsRequest>(json2);
json1.Dump("json1");
req1.Dump("Boolean ok here");
json2.Dump("json2");
req2.Dump("Boolean not ok here. Why not?");
}
// Define other methods and classes here
public class UpdateLocationsRequest
{
public string token { get; set; }
public List<LocationJson> locationList { get; set; }
}
public class LocationJson
{
public string deviceLocationId { get; set; }
public string name { get; set; }
public string desc { get; set; }
public int locType { get; set; }
public float lat { get; set; }
public float lon { get; set; }
public bool show { get; set; }
}
public class TestClass {
public string token {get; set;}
public bool share {get; set;}
}
Your json bool value is share, but in your class it's show. Adjust one or the other so they match, and you should be good to go
I found your problem. You LocationJson class has a boolean property named show whiles your json2 string has the property share. show is never updated. All other values are updated.
It is always a good thing to add breakpoints and step into your program and see what is going on.
Best of luck.
I want to do something quite simple.
I just want to take a JSON string (which I have) and populate a whole bunch of stuff with it.
The problem for me is that there are arrays hidden in array inside more arrays, and I can't get at my data.
I tried standard deserialization like so ...
var apiData = JsonConvert.DeserializeObject<RootObject>(json);
But this only lets me get into the top layer - what is in rootObject
I tried making a dictionary ...
Dictionary<string, dynamic> values = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json);
but that doesn't let me drill down either (or I can't make it).
I have set up my c# using json2c#
I've been all over the internet including here.
The closest I have got to creating anything close is an expandoObject
var converter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, converter);
which I can see from the debugger is keeping everything structured as I would like but I've no idea how to get some of the stuff out.
Long story short, its been two days now and I'm bashing my head against a brick wall.
I just want to be able to get the data out of the JSON string and I can't change that string as its not mine.
public class NewsArticlesList
{
public string title { get; set; }
public string link { get; set; }
public string source { get; set; }
public string snippet { get; set; }
}
public class jobsList
{
public string title { get; set; }
public string titleLinkUrl { get; set; }
public List<object> relatedSearchesList { get; set; }
public string formattedTraffic { get; set; }
public int trafficBucketLowerBound { get; set; }
public int interestLevel { get; set; }
public string interestColor { get; set; }
public List<NewsArticlesList> newsArticlesList { get; set; }
public double startTime { get; set; }
public string shareUrl { get; set; }
public string date { get; set; }
}
public class jobsByDateList
{
public string date { get; set; }
public string formattedDate { get; set; }
public List<jobsList> jobsList { get; set; }
}
public class RootObject
{
public string summaryMessage { get; set; }
public double dataUpdateTime { get; set; }
public List<jobsByDateList> jobsByDateList { get; set; }
public string oldestVisibleDate { get; set; }
public bool lastPage { get; set; }
}
My problem is these lists inside lists inside lists.
I can get to jobsListByDate.formattedDate but I can't get anywhere near jobsListByDate.jobsList.titleLinkUrl let alone inside the NewsArticlesList to those sources.
Apologies if this is super-easy (I hope it is) but I'm a WP8 noob.
I know there are similar threads on SO, but none of them seem to deal with such deep arrays.
I was not stipulating which branch to go down and so it was confused.
System.Diagnostics.Debug.WriteLine(apiData.jobsByDateList[0].jobsList[0].interestLevel);
I was trying to get in using
System.Diagnostics.Debug.WriteLine(apiData.jobsByDateList.jobsList.interestLevel);
and intellisense was freaking out.
With the [0] I'm now able to drill in just fine and don't need the expandoobject. Just needed to sleep on it. :-)
I have three dictionaries:
Projects
Seasons
Episodes
Each project has a list of seasons and each season can have one or more episodes.
It's basically a tree. This is what the API will provide.
I'm not sure how to do this but I was thinking something like this:
public class ProjectList
{
public List<Project> Projects
{
get;
set;
}
}
public class Project
{
public string ProjectTitle
{
get;
set;
}
public string ProjectLink
{
get;
set;
}
public List<Season> Seasons
{
get;
set;
}
}
public class Seasons
{
public string SeasonTitle
{
get;
set;
}
public string SeasonLink
{
get;
set;
}
public List<Episodes> Episodes
{
get;
set;
}
}
public class Episodes
{
public string EpisodeTitle
{
get;
set;
}
public string EpisodeLink
{
get;
set;
}
}
Is there an easier way to do this? How would I go about accomplishing this?
This is perfectly fine and probably the most straight forward and common way you'll see data with these relationships organized. If you're using json.NET converting it to json is as simple as;
string responseBody = JsonConvert.SerializeObject(ProjectListInstance);
The default serializer will handle everything for you returning the full complex object. JsonConvert is in the Newtonsoft.Json namespace and is imo the best tool for serializing and deserializing json in C#.