Could someone help me in structuring the class for below format JSON.
I have already tried http://json2csharp.com/ tool. It did not work as my list of people are dynamic, i.e. values 123, 124 etc are not pre-defined.
{
"people":
{
"123":"jack henry",
"124":"john henry",
"125":"jill henry",
"215":"jim henry",
...
}
}
public class Root
{
public Dictionary<string, string> people = new Dictionary<string,string>();
}
Using Json.NET:
Root root = new Root();
root.people.Add("123", "jack henry");
//... Add more people
string json = JsonConvert.SerializeObject(root);
Visual Studio > Edit > Paste Special > Paste JSON as classes
public class Rootobject
{
public People people { get; set; }
}
public class People
{
public string _123 { get; set; }
public string _124 { get; set; }
public string _125 { get; set; }
public string _215 { get; set; }
}
You already got an answer for your question. But, looking at the sample JSON looks like you are actually storing a list of persons. If that is the case, you might create classes like this
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class People
{
public List<Person> Persons { get; set; }
//other properties
}
And have your JSON standardized as
{
"Persons": [
{
"Id": 123,
"Name": "Jack"
},
{
"Id": 124,
"Name": "John"
}
]
}
Which will be much more meaningful and readable (by code and human).
Source: http://json2csharp.com/
public class People
{
public string __invalid_name__123 { get; set; }
public string __invalid_name__124 { get; set; }
public string __invalid_name__125 { get; set; }
public string __invalid_name__215 { get; set; }
}
public class RootObject
{
public People people { get; set; }
}
Related
I have json file, how can I deserialize this? As I understood json file had array which has 3 elements, but I didn't understand what is inside elements Id, Name, Driver and data inside Driver what is this (Driver) object?
[
{
"Id":1,
"Name":"Renault Magnum",
"Driver":{
"Name":"John",
"Surname":"Dou",
"Age":35,
"Experience":10
},
"State":"base"
},
{
"Id":2,
"Name":"Volvo FH12",
"Driver":{
"Name":"Jack",
"Surname":"Dou",
"Age":55,
"Experience":30
},
"State":"base"
},
{
"Id":3,
"Name":"DAF XF",
"Driver":{
"Name":"Jane",
"Surname":"Dou",
"Age":45,
"Experience":15
},
"State":"base"
}
]
You can use the Paste Special-Feature of Visual Studio to generate classes from a json. By applying this technique to the json above, you get the following classes as a result:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public int Id { get; set; }
public string Name { get; set; }
public Driver Driver { get; set; }
public string State { get; set; }
}
public class Driver
{
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public int Experience { get; set; }
}
This indicates that the answer to your question what is inside elements Id, Name, Drivder and data inside Driver what is this (Driver) object? is: Yes, it is an object.
I would recommend naming the elements in a useful way though ;-)
I'm trying to deserialize JSON without declaring every property in C#. Here is a cut-down extract of the JSON:
{
"resourceType": "export",
"type": "search",
"total": 50,
"timestamp": "2020-08-02T18:26:06.747+00:00",
"entry": [
{
"url": "test.com/123",
"resource": {
"resourceType": "Slot",
"id": [
"123"
],
"schedule": {
"reference": {
"value": "testvalue"
}
},
"status": "free",
"start": "2020-08-03T08:30+01:00",
"end": "2020-08-03T09:00+01:00"
}
}
]
}
I want to get the values out of entry → resource, id and start.
Any suggestions on the best way to do this?
I've made very good experiences with json2sharp. You can enter your JSON data there and it will generate the classes you need to deserialize the JSON data for you.
public class Reference
{
public string value { get; set; }
}
public class Schedule
{
public Reference reference { get; set; }
}
public class Resource
{
public string resourceType { get; set; }
public List<string> id { get; set; }
public Schedule schedule { get; set; }
public string status { get; set; }
public string start { get; set; }
public string end { get; set; }
}
public class Entry
{
public string url { get; set; }
public Resource resource { get; set; }
}
public class Root
{
public string resourceType { get; set; }
public string type { get; set; }
public int total { get; set; }
public DateTime timestamp { get; set; }
public List<Entry> entry { get; set; }
}
The next step is to choose a framework which will help you to deserialize. Something like Newtonsoft JSON.
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
If you want to get the data without declaring classes, you can use Json.Net's LINQ-to-JSON API (JToken, JObject, etc.). You can use the SelectToken method with a JsonPath expression to get what you are looking for in a couple of lines. Note that .. is the recursive descent operator.
JObject obj = JObject.Parse(json);
List<string> ids = obj.SelectToken("..resource.id").ToObject<List<string>>();
DateTimeOffset start = obj.SelectToken("..resource.start").ToObject<DateTimeOffset>();
Working demo here: https://dotnetfiddle.net/jhBzl4
If it turns out there are actually multiple entries and you want to get the id and start values for all of them, you can use a query like this:
JObject obj = JObject.Parse(json);
var items = obj["entry"]
.Children<JObject>()
.Select(o => new
{
ids = o.SelectToken("resource.id").ToObject<List<string>>(),
start = o.SelectToken("resource.start").ToObject<DateTimeOffset>()
})
.ToList();
Demo: https://dotnetfiddle.net/Qe8NB7
I am not sure why you don't deserialize the lot (even if it's minimally populated) since you have to do the inner classes anyway.
Here is how you could bypass some of the classes (1) by digging into the JObjects
Given
public class Reference
{
public string value { get; set; }
}
public class Schedule
{
public Reference reference { get; set; }
}
public class Resource
{
public string resourceType { get; set; }
public List<string> id { get; set; }
public Schedule schedule { get; set; }
public string status { get; set; }
public string start { get; set; }
public string end { get; set; }
}
public class Entry
{
public string url { get; set; }
public Resource resource { get; set; }
}
You could call
var results = JObject.Parse(input)["entry"]
.Select(x => x.ToObject<Entry>());
I know people asked and already got some answers very similar question before like this, but still, I couldn't figure it out about mine. I have a JSON file contains a multidimensional object, like below:
{
"Common": {
"Required": "Required Entry ",
"Photos": "Photos",
"Videos": "Videos",
"Register": "Register"
},
"Forms": {
"Form": "Forms",
"Name": "Name",
"Phone": "Phone",
"Email": "Email",
"Message": "Message"
},
"Sections": {
"Home": {
"EventDateTime": "",
"MainTitle": "",
"SubTitle": ""
},
"About": {},
"Venue": {},
"Schedule": {},
"Speakers": {},
"Sponsors": {},
"Price": {},
"Contact": {}
}
}
I would like to deserialize it into my view model (LanguagesViewModel) like this:
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class LanguagesViewModel
{
public Common Common { get; set; }
public Buttons Buttons { get; set; }
public Forms Forms { get; set; }
public Navbar Navbar { get; set; }
public Sections Sections { get; set; }
}
public class Common
{
public string Required { get; set; }
public string Photos { get; set; }
public string Videos { get; set; }
public string Register { get; set; }
}
public class Forms
{
public string Form { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Message { get; set; }
}
public class Sections
{
public Home Home { get; set; }
public About About { get; set; }
public Venue Venue { get; set; }
public Schedule Schedule { get; set; }
public Speakers Speakers { get; set; }
public Sponsors Sponsors { get; set; }
public Price Price { get; set; }
public Contact Contact { get; set; }
}
public class Home
{
public string EventDateTime { get; set; }
public string MainTitle { get; set; }
public string SubTitle { get; set; }
}
public class About
{
}
public class Venue
{
}
public class Schedule
{
}
public class Speakers
{
}
public class Sponsors
{
}
public class Price
{
}
public class Contact
{
}
}
Some of the snippet to do this:
using (StreamReader sr = new StreamReader(language_file_path))
{
string contents = sr.ReadToEnd();
items = JsonConvert.DeserializeObject<LanguagesViewModel>(contents);
}
Somehow, I only can get the first level of the objects, which is:
LanguagesViewModel{
Common:null,
Forms:null,
Sections:null
}
Not the second level, not the third level. Did I do something wrong or have I missed something? Very appreciated for any kind of help.
Thank you.
You can Use this static class
public static class JsonHelper
{
public static T ToObject<T>(this string content)
{
var obj = JObject.Parse(content).GetValue(typeof(T).Name);
if (obj == null)
throw new NullReferenceException();
else
return obj.ToObject<T>();
//This ToObject here is default method written in object
}
}
Usage
var mymodel= json.ToObject<Forms>();
Or create a JSON object and read it with magic strings.
//Creating your JSON object
JObject content = JObject.Parse(sr.ReadToEnd()//or your json);
//content["your object name"] let you access to you object
var common =(Common)content["Common"];
in multidimensional objects, you can access them like this.
//content["level1"]["level2"]["level3"] & ...
var sections= (Home)content["Sections"]["Home"];
Also this way may work but i prefer the way with magic strings.
dynamic jsonObject = new JObject.Parse(sr.ReadToEnd());
var common = jsonObject.Common;
You can find more in this link
I hope this Helps!
I've been trying create c# classes to map to a JSON format required by a service. But failing to find the right answer.
Here is the JSON:
{
"request": {
"path": "1",
"coverages": {
"path": "2",
"broadcastCoverage": {
"path": "3",
"name": "First Coverage",
"channel": "Channel 9",
"callSign": "DSOTM"
},
"internetCoverage": {
"path": "4",
"name": "Second Coverage",
"url": "www.stackoverflow.com"
},
"thirdCoverage": {
"path": "5",
"name": "Third Coverage",
"differentProperty": "Units"
}
}
}
}
If I put this into a JSON to C# converter I get the following:
public class BroadcastCoverage
{
public string path { get; set; }
public string name { get; set; }
public string channel { get; set; }
public string callSign { get; set; }
}
public class InternetCoverage
{
public string path { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class ThirdCoverage
{
public string path { get; set; }
public string name { get; set; }
public string differentProperty { get; set; }
}
public class Coverages
{
public string path { get; set; }
public BroadcastCoverage broadcastCoverage { get; set; }
public InternetCoverage internetCoverage { get; set; }
public ThirdCoverage thirdCoverage { get; set; }
}
public class Request
{
public string path { get; set; }
public Coverages coverages { get; set; }
}
public class RootObject
{
public Request request { get; set; }
}
But I need different types of Coverages (Broadcast, Internet, others) to be variable so I tried taking those out of the Coverages class and added a property:
public Dictionary<string, CoverageBase> CoverageList { get; set; }
Which will allow me to choose which coverages to include, the problem then becomes the CoverageList property name is in the JSON when it is serialized. I essentially would like a key/value (string, CoverageBase) without the property name.
Is there a way to add key value pairs without having the property name in the JSON? I've seen examples where this is done at the root object level but I haven't been able to find any example where it nested within the JSON.
If this can't be done with a simple object model what would be a recommended method to get the JSON built?
UPDATE: I like the answer that utilizes JsonSubTypes as it doesn't require much code, however I can't use a 3rd party library outside of json.net. Is there a way to accomplish this using a JsonConverter?
I think its possible as checked here, however it seems your app needs to reconstruct the json in a format where it includes the C# typings. More documentation here.
EDIT:
Thanks to dbc's reference I was able to dive in to the JsonSubtypes and its pretty easy to implement.
Here's my code base structure.
[JsonConverter(typeof(JsonSubtypes))]
[JsonSubtypes.KnownSubTypeWithProperty(typeof(BroadcastCoverage), "channel")]
[JsonSubtypes.KnownSubTypeWithProperty(typeof(InternetCoverage), "url")]
[JsonSubtypes.KnownSubTypeWithProperty(typeof(ThirdCoverage), "differentProperty")]
public class CoverageBase
{
public string path { get; set; }
public string name { get; set; }
}
public class BroadcastCoverage : CoverageBase
{
public string channel { get; set; }
public string callSign { get; set; }
}
public class InternetCoverage : CoverageBase
{
public string url { get; set; }
}
public class ThirdCoverage : CoverageBase
{
public string differentProperty { get; set; }
}
public class Request
{
public string path { get; set; }
public List<CoverageBase> coverages { get; set; }
}
However the Json you're receiving was not quite ideally structured, so I did some reformatting just to let it to be properly parsed.
string json = "{\"request\":{\"path\":\"1\",\"coverages\":{\"path\":\"2\",\"broadcastCoverage\":{\"path\":\"3\",\"name\":\"First Coverage\",\"channel\":\"Channel 9\",\"callSign\":\"DSOTM\"},\"internetCoverage\":{\"path\":\"4\",\"name\":\"Second Coverage\",\"url\":\"www.stackoverflow.com\"},\"thirdCoverage\":{\"path\":\"5\",\"name\":\"Third Coverage\",\"differentProperty\":\"Units\"}}}}";
var jsonReq = JObject.Parse(json);
var pathVal = jsonReq["request"]["path"].Value<string>();
var coverageObjects = jsonReq["request"]["coverages"].Value<JObject>();
var filteredObjects = coverageObjects.Children().Where(x => x.Value<JProperty>().Name.EndsWith("Coverage"));
var dictionary = filteredObjects.Select(x => new KeyValuePair<string, string>(x.Value<JProperty>().Name, x.Value<JProperty>().Value.ToString()));
// reformatted Json
var newJson = "{ \"path\":\"" + pathVal + "\", \"coverages\" : [" + String.Join(",", dictionary.Select(x => x.Value).ToList()) + "]}";
Request reqC = JsonConvert.DeserializeObject<Request>(newJson);
I want to map this JSON into a .NET class. How can I map this JSON data into a class? Please suggest how. Here is the json:
{"results": [
"43853",
"43855",
"43856",
"43857",
{
"questionType": 3,
"choiceAnswers": [123]
}
]}
The easiest solution is to use Visual Studio Edit > Paste Special > Paste Json As Classes.
But as your json is an array of different objects the .NET class will just be
public class JsonDto
{
public List<object> Results { get; set; }
}
A list of objects will be painful to work with so I recommend that you to use a typed model but then you need to specify you need to define the values, here's an example
{"results": [
{
"key1":"43853",
"key2":"43855",
"key3":"43856",
"key4":"43857",
"question": {
"questionType": 3,
"choiceAnswers": [123]
}
}
]};
public class JsonDto
{
public List<ResultDto> Results { get; set; }
}
public class ResultDto
{
public string Key1 { get; set; }
public string Key2 { get; set; }
public string Key3 { get; set; }
public string Key4 { get; set; }
public QuestionDto Question { get; set; }
}
public class QuestionDto
{
public int QuestionType { get; set; }
public List<int> ChoiceAnswers { get; set; }
}
You can use online converter to convert json data to c# models http://json2csharp.com For your json it would be something like this.
public class RootObject
{
public List<object> results { get; set; }
}