You can use json2csharp.com to Convert your json to object model
- Go to json2csharp.com
- Past your JSON in the Box.
- Clik on Generate.
- You will get C# Code for your object model
- Deserialize by
var model = JsonConvert.DeserializeObject<RootObject>(json);using NewtonJson
Here, It will generate something like this:
public class MatrixModel
{
public class Option
{
public string text { get; set; }
public string selectedMarks { get; set; }
}
public class Model
{
public List<Option> options { get; set; }
public int maxOptions { get; set; }
public int minOptions { get; set; }
public bool isAnswerRequired { get; set; }
public string selectedOption { get; set; }
public string answerText { get; set; }
public bool isRangeType { get; set; }
public string from { get; set; }
public string to { get; set; }
public string mins { get; set; }
public string secs { get; set; }
}
public class Question
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public int TypeId { get; set; }
public string TypeName { get; set; }
public Model Model { get; set; }
}
public class RootObject
{
public Question Question { get; set; }
public string CheckType { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
public string ScoreIfNoMatch { get; set; }
}
}
Then you can deserialize as:
var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);
Answer from L.B on Stack OverflowYou can use json2csharp.com to Convert your json to object model
- Go to json2csharp.com
- Past your JSON in the Box.
- Clik on Generate.
- You will get C# Code for your object model
- Deserialize by
var model = JsonConvert.DeserializeObject<RootObject>(json);using NewtonJson
Here, It will generate something like this:
public class MatrixModel
{
public class Option
{
public string text { get; set; }
public string selectedMarks { get; set; }
}
public class Model
{
public List<Option> options { get; set; }
public int maxOptions { get; set; }
public int minOptions { get; set; }
public bool isAnswerRequired { get; set; }
public string selectedOption { get; set; }
public string answerText { get; set; }
public bool isRangeType { get; set; }
public string from { get; set; }
public string to { get; set; }
public string mins { get; set; }
public string secs { get; set; }
}
public class Question
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public int TypeId { get; set; }
public string TypeName { get; set; }
public Model Model { get; set; }
}
public class RootObject
{
public Question Question { get; set; }
public string CheckType { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
public string ScoreIfNoMatch { get; set; }
}
}
Then you can deserialize as:
var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);
public static class Helper
{
public static string AsJsonList<T>(List<T> tt)
{
return new JavaScriptSerializer().Serialize(tt);
}
public static string AsJson<T>(T t)
{
return new JavaScriptSerializer().Serialize(t);
}
public static List<T> AsObjectList<T>(string tt)
{
return new JavaScriptSerializer().Deserialize<List<T>>(tt);
}
public static T AsObject<T>(string t)
{
return new JavaScriptSerializer().Deserialize<T>(t);
}
}
How to convert Json array to list of objects in c# - Stack Overflow
How can I turn JSON String into a list of objects based on number of items. - Unity Engine - Unity Discussions
Trying to Deserialize a JSON into a list of Objects so that they can be passed on to a view.
How can I turn JSON String into a list of objects based on number of items. - Unity Engine - Unity Discussions
Videos
As others have already pointed out, the reason you are not getting the results you expect is because your JSON does not match the class structure that you are trying to deserialize into. You either need to change your JSON or change your classes. Since others have already shown how to change the JSON, I will take the opposite approach here.
To match the JSON you posted in your question, your classes should be defined like those below. Notice I've made the following changes:
- I added a
Wrapperclass corresponding to the outer object in your JSON. - I changed the
Valuesproperty of theValueSetclass from aList<Value>to aDictionary<string, Value>since thevaluesproperty in your JSON contains an object, not an array. - I added some additional
[JsonProperty]attributes to match the property names in your JSON objects.
Class definitions:
class Wrapper
{
[JsonProperty("JsonValues")]
public ValueSet ValueSet { get; set; }
}
class ValueSet
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("values")]
public Dictionary<string, Value> Values { get; set; }
}
class Value
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("diaplayName")]
public string DisplayName { get; set; }
}
You need to deserialize into the Wrapper class, not the ValueSet class. You can then get the ValueSet from the Wrapper.
var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;
Here is a working program to demonstrate:
class Program
{
static void Main(string[] args)
{
string jsonString = @"
{
""JsonValues"": {
""id"": ""MyID"",
""values"": {
""value1"": {
""id"": ""100"",
""diaplayName"": ""MyValue1""
},
""value2"": {
""id"": ""200"",
""diaplayName"": ""MyValue2""
}
}
}
}";
var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;
Console.WriteLine("id: " + valueSet.Id);
foreach (KeyValuePair<string, Value> kvp in valueSet.Values)
{
Console.WriteLine(kvp.Key + " id: " + kvp.Value.Id);
Console.WriteLine(kvp.Key + " name: " + kvp.Value.DisplayName);
}
}
}
And here is the output:
id: MyID
value1 id: 100
value1 name: MyValue1
value2 id: 200
value2 name: MyValue2
http://json2csharp.com/
I found the above link incredibly helpful as it corrected my C# classes by generating them from the JSON that was actually returned.
Then I called :
JsonConvert.DeserializeObject<RootObject>(jsonString);
and everything worked as expected.
Let me prefix this by saying I am very new to all this so any help would be so very appreciated - i've been trying to crack this all day and it's been a real struggle. Im making this webapp in ASP.NET core btw. So I've managed to call the twitter api and return back some tweets as JSON depending on a search query. I am then trying to deserialize these into C# objects (using the Tweet class). I then want to pass these objects through as a list to the view for it to render them all out But I just can't seem to get it to work.
I am trying to put desrialize the JSON that comes back into Tweet objects and put them into a ViewModel and then pass the viewmodel to the view. This is what comes back from the API call so I know thats working ok. This is what the Tweet class looks like. The SocialMediaType property is a class in itself, and just has two properties on it which are an Id and name which are given default values as they will always be the same. The error pageNo need to read item by item.
string json = File.ReadAllText("myobjects.json");
var playerList = JsonConvert.DeserializeObject<List<Player>>(json);
You can use this code to write your player list to file
File.WriteAllText("myobjects.json", JsonConvert.SerializeObject(playerList));
In C# .Net core console application:
First, install Newtonsoft from NuGet by the following command.
PM> Install-Package Newtonsoft.Json -Version 12.0.2
string filePath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\")) + @"Data\Country.json";
string _countryJson = File.ReadAllText(filePath);
var _country = JsonConvert.DeserializeObject<List<Country>>(_countryJson);
I've done something like before using the JavaScript serialization class:
using System.Web.Script.Serialization;
And:
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = jss.Serialize(ListOfMyObject);
Response.Write(output);
Response.Flush();
Response.End();
3 years of experience later, I've come back to this question and would suggest to write it like this:
string output = new JavaScriptSerializer().Serialize(ListOfMyObject);
One line of code.
Hi all,
I'm playing around with JSON and I have a JSON array that I'd like to add into a Listbox. I've only ever used a single JSON before and I'm not sure how to do it with a JSON Array using NewtonSoft.
{
"1": {
"id": "628190",
"entrant": "ENTRANT NAME",
"recipient": "RECIPIENT NAME",
"task": "Task Description"
}
"2": {
"id": "628191",
"entrant": "ENTRANT NAME",
"recipient": "RECIPIENT NAME",
"task": "Task Description"
}
"3": {
"id": "628192",
"entrant": "ENTRANT NAME",
"recipient": "RECIPIENT NAME",
"task": "Task Description"
}
}I know I'm missing a foreach or something like that. In the past I've only done something like this:
{
"description": "Some description",
"reason": "Some reason"
}and I've just used this
Details detail = JsonConvert.DeserializeObject<Details>(webResult1);
Here's how to think about deserializing JSON.
There are two paths, and one is easier. The easier is to make a C# object graph that looks like the JSON object, then deserialize to it. The harder is to use the token parser or types like JObject to do the same thing with a little more effort. The harder paths are better if the JSON is really "weird" and requires special effort to get into sensible C# objects.
This isn't quite bad enough to need to use JArray. Obviously you can't make a C# object with a property named "1", "2", "3", and so on, but there's another way to go about this. Any JSON object is effectively a Dictionary<string, object>, so our first decision can be that this is our outer object.
The inner objects of this dictionary do have a well-defined type. They have four properties that are strings, though maybe for your logic "id" will be a number. So we can make an object to represent this and have a more specific Dictionary.
So I'd start with:
public class JsonTask
{
public string Id { get; set; }
public string Entrant { get; set; }
public string Recipient { get; set; }
public string Task { get; set; }
}
Then the code to get the dictionary is:
var dict = JsonConvert.DeserializeObject<Dictionary<string, JsonTask>>(json);
From there, getting an array could be:
var asArray = dict.Values.ToArray();
If order is super important, you might have to do something more complex. If you know all the properties are always sequential integers, a for loop over Keys is good enough. If they might not be ordered, you might try converting Keys to an array, sorting it, then using each key to fetch each value.
I don't think the other comment about deserializing to a list will work, generally you can only deserialize JSON arrays to lists, and this is more of an object being used as a dictionary.
That... is not an array, is it? An array is using [], you just have an object with properties 1, 2, and 3. I don't think that'd even work.
To deserialize into a list, you'd do something like JsonConvert.DeserializeObject<List<Details>>(webResult1);
Your c# class mapping doesn't match with json structure.
Solution :
class MovieCollection {
public IEnumerable<Movie> movies { get; set; }
}
class Movie {
public string title { get; set; }
}
class Program {
static void Main(string[] args)
{
string jsonString = @"{""movies"":[{""id"":""1"",""title"":""Sherlock""},{""id"":""2"",""title"":""The Matrix""}]}";
JavaScriptSerializer serializer = new JavaScriptSerializer();
MovieCollection collection = serializer.Deserialize<MovieCollection>(jsonString);
}
}
If you want to match the C# structure, you can change the JSON string like this:
{[{"id":"1","title":"Sherlock"},{"id":"2","title":"The Matrix"}]}