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);
Related
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);
I have a web service that is outputting JSON in the form
{"AppointmentList":[{"AppointmentList":{"id":"1","MeetingId":"1","MeetingName":"Test Meeting 1","Length":"90","Room":"B2C","DateTimeFrom":"1st Sept 2016","Venue":"The old pub","DateCreated":"2016-08-30 00:00:00","DateDue":"2016-09-01 00:00:00","UserId":"JohnsonPa"}},{"AppointmentList":{"id":"2","MeetingId":"2","MeetingName":"Test Meeting 2","Length":"60","Room":"B2C","DateTimeFrom":"11th Sept 2016","Venue":"The old pub","DateCreated":"2016-09-01 00:00:00","DateDue":"2016-09-12 00:00:00","UserId":"JohnsonPa"}...}]}
I am trying to deserialise this in to List. Normally, I would have a Base Class that would contain a property List AppointmentList {get; set;}, however, that would mean that I can't use type T and need a pile of duplicate code for each class.
I can certainly create BaseClass with a property public List Data {get; set;} however, as the JSON won't deserialise to Data (incorrect name) and the JSON PropertyName can't be set to the class name derived from typeof(T).ToString().
Is there a way to achieve what I'm trying to do without resorting to lots of code duplication?
I've tried casting the deserialiser to JArray and creating a reader from that, but this throws an exception.
Im not sure if this is exactly what you need, but maybe something like this would work? It allows you to successfully deserialize to a JArray like you state you tried at the end of your question.
JArray result = JsonConvert.DeserializeObject<dynamic>(json).AppointmentList;
Here how to convert it to List<object>
dynamic data = JsonConvert.DeserializeObject(json);
JArray array = data.AppointmentList;
List<object> objectList = array.ToObject<List<object>>();
What is wrong with generics? If you want a schemaless data structure use JObject or dynamic if not you can try this.
class Program
{
public const string json = #"{""AppointmentList"":[{""AppointmentList"":{""id"":""1"",""MeetingId"":""1"",""MeetingName"":""Test Meeting 1"",""Length"":""90"",""Room"":""B2C"",""DateTimeFrom"":""1st Sept 2016"",""Venue"":""The old pub"",""DateCreated"":""2016-08-30 00:00:00"",""DateDue"":""2016-09-01 00:00:00"",""UserId"":""JohnsonPa""}},{""AppointmentList"":{""id"":""2"",""MeetingId"":""2"",""MeetingName"":""Test Meeting 2"",""Length"":""60"",""Room"":""B2C"",""DateTimeFrom"":""11th Sept 2016"",""Venue"":""The old pub"",""DateCreated"":""2016-09-01 00:00:00"",""DateDue"":""2016-09-12 00:00:00"",""UserId"":""JohnsonPa""}}]}";
static void Main(string[] args)
{
var items = Newtonsoft.Json.JsonConvert.DeserializeObject<AppointmentItemList<Meeting1>>(json).GetList();
var items2 = Newtonsoft.Json.JsonConvert.DeserializeObject<AppointmentItemList<Meeting2>>(json).GetList();
Console.ReadLine();
}
public class AppointmentItemList<T>
{
public List<AppointmentItem> AppointmentList { get; set; }
public class AppointmentItem
{
public T AppointmentList { get; set; }
}
public IList<T> GetList()
{
return AppointmentList.Select(al => al.AppointmentList).ToList();
}
}
public class Meeting1
{
[Newtonsoft.Json.JsonProperty("id")]
public string Id { get; set; }
public string MeetingName { get; set; }
}
public class Meeting2
{
[Newtonsoft.Json.JsonProperty("id")]
public string Id { get; set; }
public string Room { get; set; }
}
}
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.
I have a string in JSON format as follows
string jsonStr = "{"Type":1, "Id":1000,"Date":null,"Group": "Admin","Country":"India","Type":1}";
I want to modify this string so that Id attribute should always be the first. The order of attributes matters.
Is there any way I can modify this string.
I tried searching google but did not find appropriate solution.
Any help would be appreciated.
EDIT:
I also tried to deserialize object using
object yourOjbect = new JavaScriptSerializer().DeserializeObject(jsonStr);
But here also the "type" attribute comes first. I dont find any way to move the attributes within this deserialized object
It's possible. Use the JsonProperty attribute, property Order.
http://www.newtonsoft.com/json/help/html/JsonPropertyOrder.htm.
Let me know if it works.
Instead of attempting to manipulate the order of the outputted JSON and comparing strings, I would transform both JSON strings that you want to compare, into objects and then perform your comparison. You could then compare individual properties or entire objects with something like the following:
void CompareJSON()
{
string json = #"{""Type"":1, ""Id"":1000,""Date"":null,""Group"": ""Admin"",""Country"":""India"",""Type"":1}";
string jsonToCompare = "JSON TO COMPARE";
MyObject myJsonObject = JsonConvert.DeserializeObject<MyObject>(json);
MyObject myJsonObjectToCompare = JsonConvert.DeserializeObject<MyObject>(jsonToCompare);
if (myJsonObject.Id == myJsonObjectToCompare.Id)
{
// Do something
}
}
class MyObject
{
public int Id { get; set; }
public int Type { get; set; }
public DateTime? Date { get; set; }
public string Group { get; set; }
public string Country { get; set; }
}
Please note that this example is carried out using the Newtonsoft.JSON library. More information on the library can be found here.
Just make your JSON into a c# class with Id first and then serialize it again if that is what you need. You do know that you have "Type" twice in the JSON string? In this solution it will get "fixed" so you only have it once as it should be. But if your string really is with two Type this wont work since the strings will be incorrect. If they really are like that you need to do some ugly string manipulation to fix the order but i hope the first string is incorrect only here and not in your code.
private void Test() {
string json = #"{""Type"":1, ""Id"":1000,""Date"":null,""Group"": ""Admin"",""Country"":""India"",""Type"":1}";
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
MyJsonObject myJsonObject = jsonSerializer.Deserialize<MyJsonObject>(json);
string s = jsonSerializer.Serialize(myJsonObject);
//Returns: {"Id":1000,"Type":1,"Date":null,"Group":"Admin","Country":"India"}
}
class MyJsonObject {
public int Id { get; set; }
public int Type { get; set; }
public DateTime? Date { get; set; }
public string Group { get; set; }
public string Country { get; set; }
}
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).