How to Convert JSON object to Custom C# object?
A good way to use JSON in C# is with JSON.NET
Quick Starts & API Documentation from JSON.NET - Official site help you work with it.
An example of how to use it:
public class User
{
public User(string json)
{
JObject jObject = JObject.Parse(json);
JToken jUser = jObject["user"];
name = (string) jUser["name"];
teamname = (string) jUser["teamname"];
email = (string) jUser["email"];
players = jUser["players"].ToArray();
}
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
// Use
private void Run()
{
string json = @"{""user"":{""name"":""asdf"",""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
User user = new User(json);
Console.WriteLine("Name : " + user.name);
Console.WriteLine("Teamname : " + user.teamname);
Console.WriteLine("Email : " + user.email);
Console.WriteLine("Players:");
foreach (var player in user.players)
Console.WriteLine(player);
}
Convert JSON response to Custom C# object
Use FromBody
attribute to deserialize body
[HttpPost]
public async Task<IActionResult> PostWebHook([FromBody] Root root)
{
// root is deserialized body
// modify root
...
return Ok(root);
}
How to Convert JSON object to Custom C# type object?
list1
is a list of IDTT
, not simple ints. Your json would be like this:
"list1": [ {"ID": 1000}, {"ID": 2000}, {"ID":3000}]
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
Convert JSON to C# complex object
You should remove Tree
from your JSON as Tree
is the destination type and don't need to be included in the JSON.
{
"Root": {
"children": [],
"leaves": [],
"FK": 1,
"ID": 1,
"Name": " LOGISTICS",
"Code": "PT01"
}
}
EDIT : In order to deserialize your abstract Node
elements, you will need a concrete type and a custom converter. See Deserializing a collection of abstract classes and all duplicate links listed
How to convert JSON response object (having dynamic objects) into C# classes or usable result object
try this
var jsonParsed = JObject.Parse(json);
var count = (int)jsonParsed["data"]["count"];
var taken = (int)jsonParsed["data"]["taken"];
((JObject)jsonParsed["data"]).Descendants()
.OfType<JProperty>()
.Where(attr => attr.Name == "count" || attr.Name == "taken")
.ToList()
.ForEach(attr => attr.Remove());
Data data = jsonParsed.ToObject<Data>();
data.count = count;
data.taken = taken;
classes
public class Data
{
public bool success { get; set; }
public Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, Product[]>>>>> data { get; set; }
public int count { get; set; }
public int taken { get; set; }
public class Product
{
public int balance { get; set; }
public double first { get; set; }
public double regular { get; set; }
public double final { get; set; }
public double total { get; set; }
public double charges { get; set; }
public double apr { get; set; }
public double apr_nofees { get; set; }
public int term { get; set; }
public double flat { get; set; }
public string fee_front { get; set; }
public string fee_back { get; set; }
public int fee_spread { get; set; }
[JsonProperty("ref")]
public string refer { get; set; }
public int ho { get; set; }
public int ho_a { get; set; }
public int sb { get; set; }
public string id { get; set; }
public string product_name { get; set; }
public object excess_mileage { get; set; }
}
How do I convert this JSON file into a custom c# Object
The exception you got indicates that there's something wrong with your deserialization.
I can't tell what you actually did, but if you tried to deserialize the whole json object (i.e., the whole file), you should understand that it doesn't contain a list of Products, but a more complex types' hierarchy. Thus, this line fails:
List<Product> products = JsonConvert.DeserializeObject<List<Product>>(JsonString);
I'll list two options to get things to work for you, choose whatever you feel more comfortable with.
Note that I'll use a more concise json object. In addition, I've added another object to each of the arrays, to make things more realistic (as in your file)):
{
"unique_image_url_prefixes": [],
"products_and_categories": {
"Tops": [
{
"name": "Top1",
"id": "1"
},
{
"name": "Top2",
"id": "2"
}
],
"Shirts": [
{
"name": "Shirt1",
"id": "3"
},
{
"name": "Shirt2",
"id": "4"
}
]
}
}
Option #1
Build The Class Hierarchy
Go to the post @CodingYoshi linked to, and create the class hierarchy with Visual Studio. You'll get something very similar the following hierarchy, though I'll make it more concise:
public class Rootobject
{
public object[] unique_image_url_prefixes { get; set; }
public Products_And_Categories products_and_categories { get; set; }
}
public class Products_And_Categories
{
public TopsSweaters[] TopsSweaters { get; set; }
public Shirts[] Shirts { get; set; }
}
public class TopsSweaters
{
public string name { get; set; }
public int id { get; set; }
}
public class Shirts
{
public string name { get; set; }
public int id { get; set; }
}
Deserialization
This is how you deserialize your string:
string JsonString = @"{""unique_image_url_prefixes"":[],""products_and_categories"":{""TopsSweaters"":[{""name"":""Top1"",""id"":""1""},{""name"":""Top2"",""id"":""2""}],""Shirts"":[{""name"":""Shirt1"",""id"":""3""},{""name"":""Shirt2"",""id"":""4""}]}}";
Rootobject container = JsonConvert.DeserializeObject<Rootobject>(JsonString);
You can then iterate over each array (TopsSweaters
, Shirts
) within container.products_and_categories
.
Option #2
If you'd like to use some other class hierarchy (e.g., your Product
class), you can do the following:
Build The Class Hierarchy
public class Product
{
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("id")]
public int id { get; set; }
}
// Choose either one of the following (they function the same):
public class ProductsContainer1
{
[JsonProperty("TopsSweaters")]
public List<Product> ProductsList1 { get; set;}
[JsonProperty("Shirts")]
public List<Product> ProductsList2 { get; set;}
}
public class ProductsContainer2
{
public List<Product> TopsSweaters { get; set; }
public List<Product> Shirts { get; set; }
}
// Choose either one of the following (they function the same):
public class Things1
{
[JsonProperty("unique_image_url_prefixes")]
public object[] Prefixes { get; set;}
[JsonProperty("products_and_categories")]
public ProductsContainer1 Products { get; set;}
}
public class Things2
{
public object[] unique_image_url_prefixes { get; set;}
public ProductsContainer2 products_and_categories { get; set;}
}
Deserialization
Deserialize as follows:
string JsonString = @"{""unique_image_url_prefixes"":[],""products_and_categories"":{""TopsSweaters"":[{""name"":""Top1"",""id"":""1""},{""name"":""Top2"",""id"":""2""}],""Shirts"":[{""name"":""Shirt1"",""id"":""3""},{""name"":""Shirt2"",""id"":""4""}]}}";
// Use either one of the following:
Things1 container1 = JsonConvert.DeserializeObject<Things1>(JsonString);
Things2 container2 = JsonConvert.DeserializeObject<Things2>(JsonString);
How to map fetched API data into JSON object for looping
Your models:
public class Self
{
public string href { get; set; }
}
public class Web
{
public string href { get; set; }
}
public class SourceVersionDisplayUri
{
public string href { get; set; }
}
public class Timeline
{
public string href { get; set; }
}
public class Badge
{
public string href { get; set; }
}
public class Links
{
public Self self { get; set; }
public Web web { get; set; }
public SourceVersionDisplayUri sourceVersionDisplayUri { get; set; }
public Timeline timeline { get; set; }
public Badge badge { get; set; }
}
public class Value
{
public Links _links { get; set; }
public int id { get; set; }
public string buildNumber { get; set; }
public string status { get; set; }
}
public class Root
{
public int count { get; set; }
public List<Value> value { get; set; }
}
After requesting:
string responseBody = await response.Content.ReadAsStringAsync();
if(responseBody is {Length: > 0})
{
var result= JsonSerializer.Deserialize<Root>(responseBody);
};
Related Topics
Is Is Possible to Export Functions from a C# Dll Like in VS C++
Parse Email Content from Quoted Reply
How to Check If a File Is in Use
What Is the Correct Way to Create a Single-Instance Wpf Application
How to Dynamically Compile and Execute C# Code Fragments
Retrieving Property Name from Lambda Expression
Should 'Using' Directives Be Inside or Outside the Namespace
Capture Screenshot of Active Window
How to Match an Entire String With a Regex
What's the Difference Between Invoke() and Begininvoke()
Multiple Levels in MVC Custom Routing
How to Read a Text File Reversely With Iterator in C#