Creating a C# class for JSON deserialization [duplicate] - c#

This question already has answers here:
Deserializing JSON with dynamic keys
(4 answers)
Complicated Json to C# Object Deserialize with classes
(2 answers)
Using JSON.NET to read a dynamic property name
(1 answer)
Closed 10 months ago.
I'm having an issue with JSON that I'm getting back for a hotel booking API. Essentially I'm taking the output and trying to create a class so that I can put it into an object. The problem is this: The JSON is returning objects and we can't readily use this format to make a C# class because of how it's formatted:
Example of how the JSON is formatted
Here is a snippet of it. Attributes is the highest level, then "pets" is next. The values we need for this are id: 5058 and name: Service Animals are allowed, however they are creating this "5058" and "5059" and "2050" object which is making it difficult to create a class and properly deserialize it.
I'm fairly new at C# (formerly long-time C programmer), so trying to understand the best way to make a class for something like this where the "5058" is not actually created as a class ... I would prefer if we could ingest that level into an array or list perhaps?
This is what something like json2csharp.com outputs...
public class Pets
{
public _5058 _5058 { get; set; }
public _5059 _5059 { get; set; }
public _2050 _2050 { get; set; }
}
And then
public class _5059
{
public string id { get; set; }
public string name { get; set; }
}
5059 should not be a class... That appears to be the name of the object; I want to ignore that because the ID: in the object is 5059
This wont work since there are thousands of IDs, and we're not looking to create a separate class for each ID -
I would like to make a class more like this
public class Pets
{
public string id { get; set; }
public string name {get; set; }
}
This is how I'm receiving the JSON
{
"pets":{
"5058":{
"id":"5058",
"name":"Service animals are allowed"
},
"5059":{
"id":"5059",
"name":"Service animals are exempt from fees/restrictions"
},
...
}
}
(This is a small snippet)
Again, here, they have "5059":{"id":"5059","name":"Service animals...."
So, what's the best way to ingest this with a class in C# without creating classes for the ID, the way a JSON to C# class creator would do?
Thanks for you help

That looks like a Dictionary<string, Pet> where those 5058, 5059, etc. are the keys.
public class Data
{
public Dictionary<string, Pet> pets { get; set; }
}
public class Pet
{
public string id { get; set; }
public string name { get; set; }
}
Deserialize the json as below
var data = JsonSerializer.Deserialize<Data>(json);
or if you're using Newtonsoft.Json
var data = JsonConvert.DeserializeObject<Data>(json);

Related

How can I parse JSON Array to string? [duplicate]

This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
Closed 2 years ago.
I'm trying to get JSON content with Newtonsoft.Json. To read one variable i have that method and It's working fine:
dynamic data = JObject.Parse(json);
return data.FirstName;
The problem begins if I want to read variable which is in array ex:
{"family": [{"fatherFirstName": "John", "motherFirstName": "July"}, {"fatherFirstName": "Jack", "motherFirstName": "Monika"]}
And for example I only want to get every father's first name.
Anybody know how can I do this?
Edit1:
Ok I fixed the convert from JArray to string but now there is problem that It reads family variable properly but If I want to get exact variable from Array it says that variable like this doesn't exist.
First of all, your JSON string has an invalid format. You can check it here to validate. Secondly, the best way to do this is to create a class and than use JsonConvert.DeserializeObject. On your case, here is the full working solution:
static void Main(string[] args)
{
string json = #"{'family': [{'fatherFirstName': 'John', 'motherFirstName': 'July'}, {'fatherFirstName': 'Jack', 'motherFirstName': 'Monika'}]}";
Families families = JsonConvert.DeserializeObject<Families>(json);
foreach (var family in families.family)
Console.WriteLine(family.fatherFirstName);
}
public class Families
{
public List<Family> family { get; set; }
}
public class Family
{
public string fatherFirstName { get; set; }
public string motherFirstName { get; set; }
}
public class familyData
{
public string fatherFirstName {get; set;}
public string motherFirstName {get; set;}
}
public class familyList
{
public List<familyData> family
}
and in your method
var data = JsonConvert.DeserializeObject<familyList>(json);

Serializing objects to JSON - dynamic property serialization [duplicate]

This question already has answers here:
NewtonSoft add JSONIGNORE at runTime
(7 answers)
Closed 5 years ago.
I have a class of which I serialize objects to JSON using json.net. The class has some property that I usually didn't want serialized, so I marked it with JsonIgnore.
public class SomeClass
{
[JsonIgnore]
public int ID { get; set; }
public int SecondID { get; set; }
public string Name { get; set; }
}
Now, in a different context, I wish to export objects of the same class, but here I wish to also export the ID (that I have flagged to be ignored in the first context).
Is it possible to dynamically flag a property to be ignored before serializing to JSON or do I have to write a custom serializer to achieve this?
How can I achieve the desired behavior in the simplest possible way?
Here you can make a list of properties you want to ignore :
[JsonIgnore]
public List<Something> Somethings { get; set; }
//Ignore by default
public List<Something> Somethings { get; set; }
JsonConvert.SerializeObject(myObject,
Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});

JSON deserialization, get properties name not value [duplicate]

This question already has answers here:
How can I deserialize this JSON with JsonConvert?
(2 answers)
Closed 6 years ago.
First of all, this question may have been asked before, but I couldn't find an answer due to poor wording I guess.
I get a weirdly formatted JSON string back from a WebService call
{
"id":5000174774,
"name":"company_name",
"choices":
{
"Farmway":
{
"Head Office (BSU)":[],
"Alnwick":[],
"Bury St Edmunds":[]
},
"Tate":
{
"Head Office":[],
"Tate Britain Entrance":[]
}
}
}
Here are the classes I'd like to use for deserialization
public class RootObject
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("choices")]
public Company[] Companies{ get; set; }
}
public class Company
{
public string[] Shops { get; set; }
}
I've never seen a JSON formatted like that, and I have no idea how to get the properties name instead of values. "choices" is not an array but an object, but I can't know its properties beforehand. I just want to get all companies and their shops.
I hope it makes some kind of sense.
I don't know about your deserializer, but usually a good candidate is a Dictionary:
[JsonProperty("choices")]
public Dictionary<string, Dictionary<string, List<OfSomething>> Companies { get; set; }
So, your first key is a string, with the name of the company, and the value is another dictionary, linking company BU's to list/arrays of I-don't-know-what.
If you then need to elaborate this structure into something else, you can process it with a bit of Linq.

C# Json Deserialization

I have been asked to work with json data in order to create a quiz game in windows phone. I knew that I had to use json.net to achive this which I have previously used in the past but the method I used in the past is no useful here.
My question is this. I have this json string
[{"corr":"1","q":"text.","type":"0"},
{"corr":"0","q":"text.","type":"0"},
{"corr":"1","q":"text.","type":"0"},
{"corr":"0","q":"text.","type":"0"},
{"corr":"0","q":"text.","type":"0"},
{"corr":"1","q":"text.","type":"0"},
{"corr":"4","q":"text","a":["text","text","text","text"],"type":"1"},
{"corr":"2","q":"text","a":["text","text","text","text"],"type":"1"},
{"corr":"1","q":"text","a":["text","text","text","text"],"type":"1"},
{"corr":"2","q":"text","a":["22,2%","45%","54%","67%"],"type":"1"}]
and as you can image I want to fill some List with the properties above.
I have created the following class in order to represent the json objects
public class QuizObj
{
public string corr { get; set; }
public string q { get; set; }
public string type { get; set; }
public List<string> a { get; set; }
}
but I don't really know how to use it and can't find something really relevant.
Something like this should do the trick:
var quizObjs = JsonConvert.DeserializeObject<List<QuizObj>>(serializedStringValue);
string corr = quizObjs.First().corr;
// or
foreach(var quizObj in quizObjs)
{
string corr = quizObj.corr;
// etc
}
You will need to add a reference to NewtonSoft.Json, which you can get via NuGet (if you haven't already).

How to map JSON to C# Objects

I am having issues with understanding how to make this happen.
Basically we have an API, the user sends a JSON of the format:
{
"Profile":[
{
"Name":"Joe",
"Last":"Doe",
"Client":{
"ClientId":"1",
"Product":"Apple",
"Message":"Peter likes apples"
},
"Date":"2012-02-14"
}
]
}
I have a class called Profile with parameters Name, Last, and an object as one of its members called Client as well as property Date.
Something like this:
public class Profile {
public string Name {get; set;}
public string Last {get; set;}
public Client client {get; set;}
public DateTime dDate {get; set;}
}
So basically, I am not sure how to grab the JSON and then map it to my object.
Any help with "helping" me understand would be much appreciated.
You can use Json.NET to deserialize your json string as (with some modifications to your classes)
var yourObject = JsonConvert.DeserializeObject<Root>(jsonstring);
public class Root
{
public Profile[] Profile;
}
public class Profile
{
public string Name { get; set; }
public string Last { get; set; }
public Client Client { get; set; }
public DateTime Date { get; set; }
}
public class Client
{
public int ClientId;
public string Product;
public string Message;
}
You can use a JSON library for this, for example Newtonsoft.Json which is free. It will map json to your types automatically.
Sample:
public static T Deserialize<T>(string json)
{
Newtonsoft.Json.JsonSerializer s = new JsonSerializer();
return s.Deserialize<T>(new JsonTextReader(new StringReader(json)));
}
There is also a NuGet package available.
Easiest way I know is to use JSON.Net by newtonsoft.
To make it easier to understand, I always make matching classes in C# with the same name.
Then its easier to deserialize it.
As an example, if it is an array of objects in js, it will map to a list of object with the same names in C#.
As for the date time, its a bit tricky.
Id do the client side validation and Datetime.tryParse in the serverside, itll take care of the dashes or slashes.
var serializer = new JavaScriptSerializer();
List<abc> abcList = serializer.Deserialize<List<abc>>(PassedInJsonString);
I know this is a long time question, but I would like to add one more option, which does not use third party libraries, and only uses stock .Net libraries, and is available from .Net Core 3.1 onwards.
First of all, I leave a link to the official Microsoft documentation (where you will find examples on how to serialize and deserialize json strings): https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to
Let's build on your example. We have our starting json string:
{
"Profile":[
{
"Name":"Joe",
"Last":"Doe",
"Client":{
"ClientId":"1",
"Product":"Apple",
"Message":"Peter likes apples"
},
"Date":"2012-02-14"
}
]
}
If we build a data structure that can hold that definition, it would be something like:
public class Root
{
public List<Profile> Profile { get; set; }
}
public class Profile
{
public string Name { get; set; }
public string Last { get; set; }
public Client Client { get; set; }
public string Date { get; set; }
}
public class Client
{
public string ClientId { get; set; }
public string Product { get; set; }
public string Message { get; set; }
}
Now, and finally the answer to how to deserialize a json string into a particular object without third party libraries:
Root root = JsonSerializer.Deserialize<Root>(json);
Where json is the variable that contains your json string.
I add another link of interest, the official documentation of the Deserialize(...) method: https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializer.deserialize
Something that is really useful is the exception that can be thrown, JsonException: https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonexception
DataContractJsonSerializer does the job, but it uses more sophisticated format for DateTime serialization.

Categories

Resources