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 OverflowHow can I turn JSON String into a list of objects based on number of items. - Unity Engine - Unity Discussions
Convert List<string> to JSON using C# and Newtonsoft
c# - Serializing a list to JSON - Stack Overflow
apex - JSON Array String into List - Salesforce Stack Exchange
Videos
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);
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);
}
}
The below code wraps the list in an anonymous type, and thus generates what you are looking for.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var list = new List<string> {"foo", "bar"};
var tags = new {tags = list};
Console.WriteLine(JsonConvert.SerializeObject(tags));
Console.ReadLine();
}
}
}
Arguably the easiest way to do this is to just write a wrapper object with your List<string> property
public class Wrapper
{
[JsonProperty("tags")]
public List<string> Tags {get; set; }
}
And then when serialized this gives the output you expect.
var obj = new Wrapper(){ Tags = new List<string>(){ "foo", "bar"} };
var json = JsonConvert.SerializeObject(obj);
Console.WriteLine(json);
// outputs: {"tags":["foo","bar"]}
Live example: http://rextester.com/FTFIBT36362
If using .Net 6.0 or later;
Default to using the built in System.Text.Json parser implementation with Source Generation. Its a little more typing and compiling but, is more efficient at runtime.
The "easier to code" option below, still works but, less efficiently because it uses Reflection at runtime. The new method has some intentional, by design limitations. If you can't change your model to avoid those, the Reflection based method remains available.
e.g.
using System.Text.Json;
using System.Text.Json.Serialization;
var aList = new List<MyObjectInJson>
{
new(1, "1"),
new(2, "2")
};
var json = JsonSerializer.Serialize(aList, Context.Default.ListMyObjectInJson);
Console.WriteLine(json);
return;
public record MyObjectInJson
(
long ObjectId,
string ObjectInJson
);
[JsonSerializable(typeof(List<MyObjectInJson>))]
internal partial class Context : JsonSerializerContext
{
}
If using .Net Core 3.0 to .Net 5.0, it is time to upgrade;
Default to using the built in System.Text.Json parser implementation.
e.g.
using System.Text.Json;
var json = JsonSerializer.Serialize(aList);
If stuck using .Net Core 2.2 or earlier;
Default to using Newtonsoft JSON.Net as your first choice JSON Parser.
e.g.
using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(aList);
you may need to install the package first.
PM> Install-Package Newtonsoft.Json
For more details see and upvote the answer that is the source of this information.
For reference only, this was the original answer, many years ago;
// you need to reference System.Web.Extensions
using System.Web.Script.Serialization;
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(aList);
You can also use Json.NET. Just download it at http://james.newtonking.com/pages/json-net.aspx, extract the compressed file and add it as a reference.
Then just serialize the list (or whatever object you want) with the following:
using Newtonsoft.Json;
string json = JsonConvert.SerializeObject(listTop10);
Update: you can also add it to your project via the NuGet Package Manager (Tools --> NuGet Package Manager --> Package Manager Console):
PM> Install-Package Newtonsoft.Json
Documentation: Serializing Collections
If your array continues with X4,Y4,Z4, you have a problem since, for deserializing the strong type class from the JSON, the array entries should be known. To deserialize the current JSON, use the following classes:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string X1 { get; set; }
public string Y1 { get; set; }
public string Z1 { get; set; }
public string X2 { get; set; }
public string Y2 { get; set; }
public string Z2 { get; set; }
public string X3 { get; set; }
public string Y3 { get; set; }
public string Z3 { get; set; }
}
You may read the JSON dynamically instead of deserializing the array:
using System.Text.Json.Nodes;
var jsonString = "[{\"X1\":\"x1\",\"Y1\":\"y1\",\"Z1\":\"z1\"},{\"X2\":\"x2\",\"Y2\":\"y2\",\"Z2\":\"z2\"},{\"X3\":\"x3\",\"Y3\":\"y3\",\"Z3\":\"z3\"}]";
var jsonObject = JsonNode.Parse(jsonString);
Console.WriteLine(jsonObject.ToString());
Console.WriteLine(jsonObject[0]["X1"]);
Alon.
Hi @Julio Bello ,
[{"X1":"x1","Y1":"y1","Z1":"z1"},{"X2":"x2","Y2":"y2","Z2":"z2"},{"X3":"x3","Y3":"y3","Z3":"z3"},...]
From the above JSON string, we can see that each property (key-value pair, such as "X1":"x1", "X2":"x2") has a different property name or key value, in this scenario the property is not fixed so we can directly use it as the class's property.
So, for the above JSON string, I suggest you could deserialize it uses a Dictionary, you can refer to the following sample code:
//required using System.Text.Json;
var values = new List>()
{
new Dictionary()
{
{"X1", "x1"},{"Y1", "Y1"},{"Z1", "Z1"}
},
new Dictionary()
{
{"X2", "x2"},{"Y2", "Y2"},{"Z2", "Z2"}
}
};
var jsonstring = JsonSerializer.Serialize(values);
//jsonstring: [{"X1":"x1","Y1":"Y1","Z1":"Z1"},{"X2":"x2","Y2":"Y2","Z2":"Z2"}]
var reult1 = JsonSerializer.Deserialize>>(jsonstring);
var test = new TestModel()
{
Item = new List>()
{
new Dictionary()
{
{"X1", "x1"},{"Y1", "Y1"},{"Z1", "Z1"}
},
new Dictionary()
{
{"X2", "x2"},{"Y2", "Y2"},{"Z2", "Z2"}
}
}
};
var jsonstring2 = JsonSerializer.Serialize(test);
//josnstring2: {"Item":[{"X1":"x1","Y1":"Y1","Z1":"Z1"},{"X2":"x2","Y2":"Y2","Z2":"Z2"}]}
var result2 = JsonSerializer.Deserialize(jsonstring2);
The TestModel
public class TestModel
{
public List> Item { get; set; }
}
The output is like this:
And this sample code:
var jsonstr = "[{\"X1\":\"x1\",\"Y1\":\"Y1\",\"Z1\":\"Z1\"},{\"X2\":\"x2\",\"Y2\":\"Y2\",\"Z2\":\"Z2\"}]";
var result3 = JsonSerializer.Deserialize>>(jsonstr);
The result:
After that you can find the data from the Dictionary. More detailed information about Dictionary, see Dictionary Class
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion
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.
I'll elaborate a bit more on ChrisR awesome answer and bring images from his awesome reference.
A valid JSON always starts with either curly braces { or square brackets [, nothing else.
{ will start an object:

{ "key": value, "another key": value }
Hint: although javascript accepts single quotes
', JSON only takes double ones".
[ will start an array:

[value, value]
Hint: spaces among elements are always ignored by any JSON parser.
And value is an object, array, string, number, bool or null:

So yeah, ["a", "b"] is a perfectly valid JSON, like you could try on the link Manish pointed.
Here are a few extra valid JSON examples, one per block:
{}
[0]
{"__comment": "json doesn't accept comments and you should not be commenting even in this way", "avoid!": "also, never add more than one key per line, like this"}
[{ "why":null} ]
{
"not true": [0, false],
"true": true,
"not null": [0, 1, false, true, {
"obj": null
}, "a string"]
}
Your JSON object in this case is a list. JSON is almost always an object with attributes; a set of one or more key:value pairs, so you most likely see a dictionary:
{ "MyStringArray" : ["somestring1", "somestring2"] }
then you can ask for the value of "MyStringArray" and you would get back a list of two strings, "somestring1" and "somestring2".
In ReturnData make the members public. When I do I get:
{"Type":"type1","Items":[{"Name":"test1","Value":"result1"},{"Name":"test2","Value":"result2"}]}
So you almost had it and now you do have it.
A .NET Fiddle for this is at ObjectToJSON.
When there are internal properties mark them as a JsonProperty, otherwise go with SimpleSamples recommendation.
using System.Collections.Generic;
using System.Diagnostics;
using Newtonsoft.Json;
namespace ObjectToJson
{
class Program
{
static void Main(string[] args)
{
var i1 = new Item
{
Name = "test1",
Value = "result1"
};
var i2 = new Item
{
Name = "test2",
Value = "result2"
};
ReturnData returnData = new ReturnData();
var items = new List {i1, i2};
returnData.Type = "type1";
returnData.Items = items;
var json = JsonConvert.SerializeObject(returnData, Formatting.Indented);
Debug.WriteLine(json);
}
}
class ReturnData
{
[JsonProperty]
internal string Type { get; set; }
[JsonProperty]
internal List Items { get; set; }
}
public class Item
{
public string Name { get; set; }
public string Value { get; set; }
}
}
Output
{
"Type": "type1",
"Items": [
{
"Name": "test1",
"Value": "result1"
},
{
"Name": "test2",
"Value": "result2"
}
]
}