Convert Json String to C# Object List
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);
convert json to c# list of objects
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);
}
}
Cannot convert JSON string to List of object
This is because you need a container class at the top that has this list of orders as a property inside of it:
public class MyData
{
public List<FoodItem> Orders { get; set; }
{
var data = JsonConvert.DeserializeObject<MyData>(strProductsInCart);
var items = data.Orders;
Also, make sure you have public properties that match the name in the JSON. They can be Pascal case, too.
How to convert a Json string to List in c#
If you don't want to create a class :
You can use JObject.Parse()
method for deserializing dynamically.
Convert JSON String To C# Object
It looks like you're trying to deserialize to a raw object. You could create a Class that represents the object that you're converting to. This would be most useful in cases where you're dealing with larger objects or JSON Strings.
For instance:
class Test {
String test;
String getTest() { return test; }
void setTest(String test) { this.test = test; }
}
Then your deserialization code would be:
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Test routes_list =
(Test)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
More information can be found in this tutorial:
http://www.codeproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx
Deserialize json to List object in C#
There is an error in your json - it's missing a closing ]
for the array (I'll assume it's a typo).
The real problem is that you need a wrapper class to represent the data
node of the json which should contain a list (or array) of ExPositions
. The makerPositions
and takerPositions
should also become lists (or arrays) too. Add the following class and update the position properties of ExPositions
:
public class Data
{
public List<ExPositions> data { get; set; }
}
// change positions to use a List too
public class ExPositions
{
...
public List<Positions> makerPositions { get; set; }
public List<Positions> takerPositions { get; set; }
}
Then you can deserialize using:
var result = JsonSerializer.Deserialize<Data>(json);
It's not clear where the ""total"": 2
property should be in your models (it's not clear in the json because of the issue I mentioned), you could add it to the Data
class above (if it belongs there).
Online demo
What is best way to convert json string into array of objects?
I recommend to install Newtonsoft.Json via the NuGet package manager. Then decorate the members of the POCO class with the JsonProperty
attribute to tell the serializer which property matches to a specific JSON key:
public class MyJsonObject
{
[JsonProperty("Value")]
string Value { get; set; }
[JsonProperty("Name")]
string Name { get; set; }
}
You can the deserialize the JSON to a corresponding object instance:
var jsonString = "[{\"Value\": \"1\", \"Name\": \"One\"}, {\"Value\": \"2\", \"Name\": \"Two\"}]";
List<MyJsonObject> myJsonObjects = JsonConvert.DeserializeObject<List<MyJsonObject>>(jsonString);
Convert Json to explicit new object, List initialization c#
You can use online services like https://www.jsonutils.com/
or
function Convert(jsonStr, classNr) {
var i = classNr == undefined ? 0 : classNr;
var str = "";
var json = JSON.parse(jsonStr);
for (var prop in json) {
if (typeof(json[prop]) === "number") {
if (json[prop] === +json[prop] && json[prop] !== (json[prop] | 0)) {
str += prop + " = " + json[prop] + "M, ";
} else {
str += prop + " = " + json[prop] + ", ";
}
} else if (typeof(json[prop]) === "boolean") {
str += prop + " = " + json[prop] + ", ";
} else if (typeof(json[prop]) === "string") {
str += prop + ' = "' + json[prop] + '", ';
} else if (json[prop] == null || json[prop] == undefined) {
str += prop + ' = null, ';
} else if (typeof(json[prop]) === "object") {
str += prop + " = " + Convert(JSON.stringify(json[prop]), i++) + ", ";
}
}
if (str.endsWith(', ')) {
str = str.substring(0, str.length - 2);
}
return "new Class" + i + "{ " + str + " }";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="tin" cols="100" rows="6">
{"A":12}
</textarea>
<input type="button" value="Just do it!" onclick="$('#result').text(Convert($('#tin').val()));" />
<div id="result"></div>
Convert json array into List of Objects
Based on the shown JSON array and the error message indicating that you are trying to convert an array to a single object, it looks like you were suppose to do
var RoleList = JsonConvert.DeserializeObject<List<UserAddRoleListViewModel>>(Input.RoleList);
in order to parser the JSON correctly into a List<>
Related Topics
Ide's for C# Development on Linux
Using .Net 4.5 Async Feature for Socket Programming
Is the Use of Dynamic Considered a Bad Practice
ASP.NET MVC 5 - Identity. How to Get Current Applicationuser
Programmatically Add Column & Rows to Wpf Datagrid
Getting Path Relative to the Current Working Directory
C# Webbrowser Control - Form Submit Not Working Using Invokemember("Click")
Why Doesn't C# Support the Return of References
Test If a Property Is Available on a Dynamic Variable
Do Static Members Ever Get Garbage Collected
Close a Messagebox After Several Seconds
Find a String Between 2 Known Values
When Should I Use Async Controllers in ASP.NET MVC
How to Hide Only the Close (X) Button
Inheritance from Multiple Interfaces with the Same Method Name