Parse Json response in C# using Newtonsoft.Json nuget - json

I have the below json response. How to read the CustomerList data from the json response. I will bind this data to a gridview. Using the Newtonsoft.Json nuget.
{
"Status": "OK",
"StatusCode": "200",
"payload":{
"SentItemCount": "65",
"MatchingItemCount": "64",
"CustomerList": [
{
"EntityName": "Franklin LLC",
"EntityID": "06012",
"ContactNum": "913-022-8187"
},
{
"EntityName": "Stanley Firm LLC",
"EntityID": "02398",
"ContactNum": "832-980-2056"
},
{
"EntityName": "Zneith Systems LLC",
"EntityID": "05801",
"ContactNum": "482-120-9406"
}
]
}
}

I don't know what kind of gridview you are using but you can get data from json by 2 ways
using Newtonsoft.Json;
var jsonParsed=JObject.Parse(json);
DataTable dataTable=jsonParsed["payload"]["CustomerList"].ToObject<DataTable>();
// or
List<Customer> customerList=jsonParsed["payload"]["CustomerList"].ToObject<List<Customer>>();
Now you can use or dataTable or customer list as a source to your gridview
if you decided to use a list , you will need to create this class
public class Customer
{
public string EntityName { get; set; }
public string EntityID { get; set; }
public string ContactNum { get; set; }
}

Related

stream writer is not writing to JSON file in webapi

Im trying to write data in a JSON file using webapi but stream writer is not writing data to the file.
JSON File :
{
"Students": [
{
"id": 1,
"name": "Ravi",
"department": "IT"
},
{
"id": 2,
"name": "Raj",
"department": "hr"
},
{
"id": 3,
"name": "avi",
"department": "it"
},
{
"id": 4,
"name": "rome",
"department": "HR"
},
{
"id":5,
"name": "virat",
"department": "HR"
},
{
"id":6 ,
"name": "Tushar",
"department": "RM"
}
]
}
Class
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}
public class Students
{
public List<Student> students { get; set; }
}
Api controller: [HttpPost] method for writing data to the json file.
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
[HttpPost]
public IActionResult Add(Students _Student)
{
using (var fs = new FileStream("C:/Users/tanmay_pawar/source/repos/CRUDAPI/CRUDAPI/people.json", FileMode.Append))
using (var sw = new StreamWriter(fs))
{
sw.WriteLine(_Student);
}
}
The data recieved in by _Student is not getting added to the json file.
try this
public IActionResult Add(Students _Student)
{
if(_Student==null || _Student.students==null) return null;
var filePath = #"C:\Users\....\..json";
var json = File.ReadAllText(filePath);
Students students = JsonConvert.DeserializeObject<Students>(json);
students.students.AddRange(_Student.students);
json=JsonConvert.SerializeObject(students);
File.WriteAllText(filePath, json);
}
Try the code like below:
[HttpPost]
public IActionResult Add(Students _Student)
{
string jsonresult = JsonConvert.SerializeObject(_Student);
string path = #"C:\c\people.json";
using(var tw=new StreamWriter(path,true))
{
tw.WriteLine(jsonresult.ToString());
tw.Close();
}
return Ok();
}
result:
Update more picture, add data inside the existing JSON file.

How to prepare json or json array for api in .net core using httpclient

I want to prepare a json like below using c#. I want to use it for post api call. How can I do it?
{
"inputs": [
{
"person": {
"name": "xyz",
"country": "india",
"phone": "9999999999",
}
},
{
"person": {
"name": "abc",
"country": "india",
"phone": "8888888888",
}
}
]
}
If you want to bind json array from appsetting.json to class, you can use following code:
create three models
public class person
{
public string name { get; set; }
public string country { get; set; }
public string phone { get; set; }
}
public class inputs
{
public person person { get; set; }
}
public class conf
{
public inputs[] inputs { get; set; }
}
Inject them into container in program.cs(.Net 6)
builder.Services.Configure<conf>(builder.Configuration);
Then in your controller, Using Dependency Injection in the Constructor to Get the Value
public class HomeController : Controller
{
private readonly IOptions<conf> _option;
public HomeController(ILogger<HomeController> logger, IConfiguration configuration,IOptions<conf> option)
{
_option = option;
}
Finally, You can use model's properties to get the value from appsetting.json

How to extract only part of the JSON and de-serialize it in .netcore

I have .net core application , where an API is called through HTTPClient.
The response for that API in JSON format is as follows:
{
"ID": 25,
"Customer": "CustomerName",
"total": 100,
"details": [
{
"ItemId": "Item1",
"ItemName": "Name1",
"Price": "10"
},
{
"ItemId": "Item2",
"ItemName": "Name2",
"Price": "50"
},
{
"ItemId": "Item3",
"ItemName": "Name3",
"Price": "40"
}
]
}
I get this response from -- > var response = client.GetAsync(ApiPath).Result;
Now from the response variable I need details only for details like :
{
{
"ItemId": "Item1",
"Price": "10"
},
{
"ItemId": "Item2",
"Price": "50"
},
{
"ItemId": "Item3",
"Price": "40"
}
}
I have a DTO class like this :
public class ItemDetails
{
public string ItemId { get; set; }
public string Price { get; set; }
}
Can anyone help in extracting the details according to the DTO class from the main variable "response".
Many thanks!
Try this if you are using newtonsoft
var token = JObject.Parse(response);//load
var detailsToken = token.SelectToken("details");//select
var itemDetails = detailsToken.ToObject<ItemDetails[]>(); //cast to array
Only the properties that exist on ItemDetails will be mapped
You can deserialize the response into an object and take whatever you like from it.
Use the built-in JSON library in .net-core as following
using System.Text.Json;
using System.Text.Json.Serialization;
then make a Response classes to contain the Response values
public class ResponseObject
{
public int ID { get; set; }
public string Customer { get; set; }
[JsonPropertyName("total")]
public int Total { get; set; }
[JsonPropertyName("details")]
public ItemDetails[] Details { get; set; }
}
public class ItemDetails
{
public string ItemId { get; set; }
public string ItemName { get; set; }
public string Price { get; set; }
}
finally, deserialize and extract whatever you like as following
var o = JsonSerializer.Deserialize<ResponseObject>(response);
ItemDetails[] itemDetails= o.Details;

How to fix, MVC model null issue if int is pass as null from json

I am using formio to produce forms from json in my asp.net core mvc web application. My model definition is given below.
public class MyRootModel
{
public Data data { get; set; }
public class Data
{
public Client client { get; set; }
public Contact contact { get; set; }
}
}
public class Client
{
public string Forename { get; set; }
public string Surname { get; set; }
public int? Gender { get; set; }
public DateTime DateofBirth { get; set; }
}
public class Contact
{
public string City { get; set; }
public string Street { get; set; }
public string Street2 { get; set; }
}
The post method on my controller is given below.
[HttpPost]
public MyResponse Next([FromBody] MyRootModel formCollection)
{
MyResponse myResponse = new MyResponse ();
myResponse.ReturnType = "Success";
myResponse.ReturnMessage = "Well done";
return myResponse ;
}
The Gender on the form is a html5 select type. When the form is submitted, formCollection object on my controller is initialised automatically as json is passed from the client side. However, if user does not select any value in the Gender drop down, then the formCollection is appearing as null. I have looked at the json being passed and noticed that "gender": "null" is passed and this is the reason formCollection is appearing null. Even though I have defined Gender as int? in my client model.
I am displaying json submitted from the form below for both scenarios. The first scenario works fine when user selects Gender.
formCollection is initialised properly
{
"data": {
"client": {
"forename": "abc",
"surname": "def",
"gender": 2
},
"contact": {
"city": "ghi",
"street": "jkl"
},
"submit": true
},
"metadata": {}
}
formColletion is becoming null when following json is passed
{
"data": {
"client": {
"forename": "dsfaasdf",
"surname": "asdf",
"gender": "null"
},
"contact": {
"city": "asdf",
"street": ""
},
"submit": true
},
"metadata": {}
}
I thought that int? allows null so I changed the Gender type from int to int? but still not working.
{
"data": {
"client": {
"forename": "dsfaasdf",
"surname": "asdf",
"gender": null
},
"contact": {
"city": "asdf",
"street": ""
},
"submit": true
},
"metadata": {}
}
Try passing the gender as null instead of "null".This is beacause the gender propert in the model class Client in your code ,is in int but you are trying to pass a string.

How to parse the Json data in WP8?

I'm newbie to windows phone 8 development. I am working on application in which I need parse the Json. please help me with this json data
{
"School": [
{
"info": {
"name": "Dary",
"description": "Student",
"startAt": "",
"endAt": "",
"status": "approved",
"type": 7
},
"gui": {
"size": 60,
"sizeMB": "1.7 M"
}
},
{
"info": {
"name": "Henry",
"description": "Student",
"startAt": "",
"endAt": "",
"status": "approved",
"type": 7
},
"gui": {
"size": 60,
"sizeMB": "1.7 M"
}
}
]
}
this is class
public class Info
{
public string name { get; set; }
public string description { get; set; }
public string startAt { get; set; }
public string endAt { get; set; }
public string status { get; set; }
public int type { get; set; }
}
public class Gui
{
public int size { get; set; }
public string sizeMB { get; set; }
}
public class School
{
public Info info { get; set; }
public Gui gui { get; set; }
}
public class RootObject
{
public List<School> School { get; set; }
}
Thanks in advance.
As Peter Torr suggests, JSON.NET is a great option. There is a DataContractJsonSerializer for serialization in the .net framework, but its not very robust. You can easily add JSON.NET to your project with Nuget. Place your json in a string variable
string json = "<<your json string>>"
or read from a file
string json = File.ReadAllText("<<path to file>>");
Then, the following code will deserialize your text.
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
You can lose the root object (it looks like it came from a javascript to C# converter) if you keep only the json array (the text between the brackets [] ), and then you can deserialize just the array.
List<School> school = JsonConvert.DeserializeObject<List<School>>(json);