How do I create a Dto in C# Asp.Net from a fairly complex Json Response
Copy the JSON and then in Visual Studio, in the menu bar go to: Edit > Paste Special > Paste JSON as Classes:
And it will produce the following for your JSON:
public class Rootobject {
public Response response { get; set; }
}
public class Response {
public Result result { get; set; }
public string uri { get; set; }
}
public class Result {
public Leads Leads { get; set; }
}
public class Leads {
public Row[] row { get; set; }
}
public class Row {
public string no { get; set; }
public FL[] FL { get; set; }
}
public class FL {
public string val { get; set; }
public string content { get; set; }
}
You can also do the same with XML by choosing the Paste XML as Classes option.
How do i convert this JSON object into C# code?
You could try to deserialize to something like this:
var charSet = JsonConvert.DeserializeObject<Dictionary<char, int[][]>>(json);
var valueSet = charSet['-'];
How would I create C# Object with this JSON
You can try using Json.NET
string result = "{'result':{'appid':295110,'contextid':1,'items':{'Skin: Graffiti Hunting Rifle':11990}}}";
var jsonData = JObject.Parse(result);
MessageBox.Show(jsonData["result"]["appid"].ToString());
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);
Deserializing json response in c#
You'll want this:
class LoginResponse
{
[JsonProperty("odata.metadata")]
public String ODataMetadata { get; set; }
[JsonProperty("value")]
public List<Vehicle> Vehicles { get; set; }
}
class Vehicle
{
// same as before...
}
LoginResponse response = JsonConvert.DeserializeObject<Vehicle>( loginJsonString );
foreach( Vehicle veh in response.Vehicles )
{
}
Parsing data from json in C#
You could declare a class like the following
public class Country
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("nicename")]
public string Name { get; set; }
}
and then deserialize the json as below:
var responseCountries = JsonConvert.DeserializeObject<IEnumerable<Country>>(content);
How can I access this JSON values in C#
First create C# classes to mimic the structure for your JSON structure by following the steps in my answer here.
Then simply do this:
var data = JsonConvert.DeserializeObject<Rootobject>("YourJsonString");
var latLng = data.results[0].locations[0].latLng;
var lat = latLng.lat;
var lng = latLng.lng;
How can get data from Json array in c#?
You can get each value like this, then it is upto you which value you need to choose.
foreach (JObject content in test1.Children<JObject>())
{
string Id = content["id"].ToString();
string email = content["email"].ToString();
}
By the way below is your correct formatted Json.
[{"id":11,"userName":null,"passWord":null,"email":"someone@gmail.com","mobile":"9423422882","fullName":"Ramesh Sharma","location":"Rajkot","city_id":1}]
Related Topics
How to Use Visual Studio Code to Develop Unity3D Projects in Ubuntu
Conditional Operator Assignment with Nullable<Value> Types
In a "Using" Block Is a SQLconnection Closed on Return or Exception
How to Determine the Owner of a Process in C#
Why Is It Bad to Use an Iteration Variable in a Lambda Expression
How to Load Dll 'Sqlite.Interop.Dll'
How to Get Text Formatting with Itextsharp
Globally Catch Exceptions in a Wpf Application
Where Is the Application.Doevents() in Wpf
Differencebetween Task.Run() and Task.Factory.Startnew()
Hide Console Window from Process.Start C#
How to Safely Call an Async Method in C# Without Await
Return File in ASP.NET Core Web API