How to delete Json particular element in C#? - json

public class students
{
public int ID { get; set; }
public string fName { get; set; }
public string mName { get; set; }
public string lName { get; set; }
public string Dept { get; set; }
public string Degree { get; set; }
public _Semister[] ComplitedSemister { get; set; }
public string SemesterCode { get; set; }
public string Year { get; set; }
}
public class _Semister
{
public int Id { get; set; }
public string Name { get; set; }
public string Instructor { get; set; }
public int Credit { get; set; }
}
This is My student class
[
{
"ID": 101,
"fName": "Kamal",
"mName": "Faheem",
"lName": "Khabib",
"Dept": "CSE",
"Degree": "BSC",
"ComplitedSemister": [
{
"Id": 2001,
"Name": "OOP",
"Instructor": "Jamal",
"Credit": 2354
}
],
"SemesterCode": "Summer",
"Year": "2014"
},
{
"ID": 454,
"fName": "fdgfdg",
"mName": "sgdfsd",
"lName": "sdfgg",
"Dept": "fdgsdf",
"Degree": "sfdgdf",
"ComplitedSemister": [
{
"Id": 324,
"Name": "cgbf",
"Instructor": "dgfd",
"Credit": 54
}
],
"SemesterCode": "Ummer",
"Year": "3423"
}
]
This is my Json File. I want to delete all element for a particular ID. For example, for ID = 101 I want delete whole data for this ID. SO the next ID = 454 become the first student in json file. But I can't Delete . SO how can I delete ?

You can do it by 2 ways ( I am using Newtonsoft.Json. You can install it by Nuget)
Parse Json to a JArray. Remove item from array. Serialize the JArray.
//your json
var json="[{\"ID\":101,\"fName\":\"Kamal\",\"mName\":\"Faheem\",\"lName\":\"Khabib\",\"Dept\":\"CSE\",\"Degree\":\"BSC\",\"ComplitedSemister\":[{\"Id\":2001,\"Name\":\"OOP\",\"Instructor\":\"Jamal\",\"Credit\":2354}],\"SemesterCode\":\"Summer\",\"Year\":\"2014\"},{\"ID\":454,\"fName\":\"fdgfdg\",\"mName\":\"sgdfsd\",\"lName\":\"sdfgg\",\"Dept\":\"fdgsdf\",\"Degree\":\"sfdgdf\",\"ComplitedSemister\":[{\"Id\":324,\"Name\":\"cgbf\",\"Instructor\":\"dgfd\",\"Credit\":54}],\"SemesterCode\":\"Ummer\",\"Year\":\"3423\"}]";
var jArray=JArray.Parse(json);
var itemToRemove = (JToken) jArray.Where(a => (int) a["ID"]==101).First();
jArray.Remove(itemToRemove);
json=jArray.ToString();
Deserialize JSON to strongly-typed list of items. Remove item from list. Serialize the list.
var json= ...your json..;
var jDeserialized= JsonConvert.DeserializeObject<List<students>>(json);
var removeItem=jDeserialized.Where(d =>d.Id==101 ).First();
jDeserialized.Remove(removeItem);
json=JsonConvert.SerializeObject (jDeserialized, Newtonsoft.Json.Formatting.Indented);
result json
[
{
"ID": 454,
"fName": "fdgfdg",
"mName": "sgdfsd",
"lName": "sdfgg",
"Dept": "fdgsdf",
"Degree": "sfdgdf",
"ComplitedSemister": [
{
"Id": 324,
"Name": "cgbf",
"Instructor": "dgfd",
"Credit": 54
}
],
"SemesterCode": "Ummer",
"Year": 3423
}
]

Related

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;

Xamarin Refit - Newtonsoft.Json.JsonSerializationException

I have some problems with JSON Serialization.
When I try to deserialize my JSON Object, it returns me this error :
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Project.Models.BookModel' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
My problem here is that I have to deserialize my object in two different ways : In a JSON array(e.g.[1,2,3]) to extract "_id", "user" and "name", and then in a JSON array(e.g.["name":"value"]) to extract "books". And I don't know how to do it. Or more precisely, I don't know if it's posible with Refit.
Here is my JSON :
[
{
"_id": "5c014a1e43b6804ed7b642b2",
"__v": 0,
"user": "5c014a1d43b6804ed7b642b1",
"name": "Favoris",
"books": [
{
"_id": "5a8f12e16a16fa06d1f5b0cb",
"title": "Harry Potter et la Chambre des Secrets",
"author": {
"_id": "5a8f12e16a16fa06d1f5b0bd",
"name": "J K Rowling",
"__v": 0
},
"literaryGenre": "Juvenile Fiction",
"isbn": 9781781101049,
"externalImage": "...",
"__v": 0,
"content": {
"brief": "test1"
}
},
{
"_id": "5a8f12e16a16fa06d1f5b0d0",
"title": "Harry Potter et la Coupe de Feu",
"author": {
"_id": "5a8f12e16a16fa06d1f5b0bd",
"name": "J K Rowling",
"__v": 0
},
"literaryGenre": "Juvenile Fiction",
"isbn": 9781781101063,
"externalImage": "...",
"__v": 0,
"content": {
"brief": "test2"
}
}
]
}
]
Here is my code :
public async void ViewLibrary()
{
IProjectApi response = ProjectRepository.Instance.ProjectApi;
List<LibraryModel> library = await response.GetLibrary("5c014a1d43b6804ed7b642b1");
this.LibraryItems = library;
}
And my object LibraryModel :
public class LibraryModel
{
public string _id { get; set; }
public string user { get; set; }
public string name { get; set; }
public BookModel books { get; set; }
}
And my method GetLibrary :
[Get("/api/library/user/{UserId}")]
Task<List<LibraryModel>> GetLibrary(string UserId);
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'Project.Models.BookModel' because the type requires a JSON object
(e.g. {"name":"value"})
In json result your BookModel returning multiple records, so it should be defined as List<BookModel>.
In LibraryModel try using public List<BookModel> books { get; set; }.
Implement these classes anywhere in your code and try to deserialize your json with these classes.
public class Author
{
public string _id { get; set; }
public string name { get; set; }
public int __v { get; set; }
}
public class Content
{
public string brief { get; set; }
}
public class Book
{
public string _id { get; set; }
public string title { get; set; }
public Author author { get; set; }
public string literaryGenre { get; set; }
public object isbn { get; set; }
public string externalImage { get; set; }
public int __v { get; set; }
public Content content { get; set; }
}
public class RootObject
{
public string _id { get; set; }
public int __v { get; set; }
public string user { get; set; }
public string name { get; set; }
public List<Book> books { get; set; }
}

asp.net core 2.1 json serialization null array is not ignored

I have the following classes:
FormGroupModel has a list of FormFieldModel which has a list of FieldOptionModel.
public class FormGroupModel
{
public string GroupLabel { get; set; }
public IEnumerable<FormFieldModel> Fields { get; set; }
}
public class FormFieldModel
{
public string Name { get; set; }
public string Label { get; set; }
public string ControlType { get; set; }
public IEnumerable<FieldOptionModel> Options { get; set; }
}
public class FieldOptionModel
{
public string Value { get; set; }
public string Label { get; set; }
}
I configured Json serializationsettings in Startup.cs to NullValueHandling.Ignore. Null values for my other API return values are all ignored as expected. This object serialization still does not get rid of the Options array when it's empty. I also tried DefaultValueHandling.Ignore but does not work either. How can I get the Options list to be ignored when empty?
[
{
"groupLabel": "Basic Information",
"fields": [
{
"name": "ProjectDescription",
"label": "Project Description",
"controlType": "multiline",
"options": []
},
{
"name": "ProjectId",
"label": "Project Id",
"controlType": "textfield",
"options": []
},
{
"name": "ProjectName",
"label": "Project Name",
"controlType": "textfield",
"options": []
},
{
"name": "ProjectScope",
"label": "Project Scope",
"controlType": "multiline",
"options": []
}

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);

Json Net hierarchy class

I am using Newtonsoft.Json on my VB.Net, and having trouble with json deserialization.
Totally a noob on this. A simple class hierarchy, I can do it... but a more complex like the one below, totally an idiot.
Can someone help me to build the serialize class hierarchy from this JSON??
{
"user": {
"user_id": 123456,
"total": 100,
"rewards": 0
},
"workers": {
"1": {
"worker_name": "rainfall_home",
"rate": 0,
"shares": 0
},
"2": {
"worker_name": "rainfall_office",
"rate": 7358.71,
"shares": 96564
},
"3": {
"worker_name": "rainfall_rig",
"rate": 0,
"shares": 77208
},
"4": {
"worker_name": "rainfall_s11",
"rate": 178365.22,
"shares": 3760356
},
"5": {
"worker_name": "rainfall_s12",
"rate": 196537.7,
"shares": 4152710
}
},
"total": {
"total_user": 5,
"record_date": 2
}
}
And how do I get the workers length(total) and loop with it, so i can get record for each worker? Since worker can keep adding up.
Thanks in advance.
As you are trying to get the total number of workers and you are saying that workers can keep adding up, then I would propose you to restructure your JSON (if you have scope to modify) so that the workers can be managed as an array instead of adding it like an object each time a new worker is needed to add to JSON. Please see the proposed JSON below:
{
"user": {
"user_id": 123456,
"total": 100,
"rewards": 0
},
"workers": [
{
"worker_name": "rainfall_home",
"rate": 0,
"shares": 0
},
{
"worker_name": "rainfall_office",
"rate": 7358.71,
"shares": 96564
},
{
"worker_name": "rainfall_rig",
"rate": 0,
"shares": 77208
},
{
"worker_name": "rainfall_s11",
"rate": 178365.22,
"shares": 3760356
},
{
"worker_name": "rainfall_s12",
"rate": 196537.7,
"shares": 4152710
}
],
"total": {
"total_user": 5,
"record_date": 2
}
}
Now your new classification is below:
public class RootObject
{
public User user { get; set; }
public List<Worker> workers { get; set; }
public Total total { get; set; }
}
public class User
{
public int user_id { get; set; }
public int total { get; set; }
public int rewards { get; set; }
}
public class Worker
{
public string worker_name { get; set; }
public double rate { get; set; }
public int shares { get; set; }
}
public class Total
{
public int total_user { get; set; }
public int record_date { get; set; }
}
Now you can easily loop through each worker to get one's details like below:
string json = "YOUR_JSON_STRING";
RootObject rootObject = JsonConvert.DeserializeObject<RootObject> ( json );
Console.WriteLine("Total no. of workers: {0}", rootObject.workers.Count);
foreach ( Worker worker in rootObject.workers )
{
Console.WriteLine("Name: {0}, Rate: {1}, Shares: {2}", worker.worker_name, worker.rate.ToString("F2", CultureInfo.InvariantCulture), worker.shares);
}
If your JSON data is from an outside API, then you can classify it like below:
public class RootObject
{
public User user { get; set; }
public Dictionary<string, Worker> workers { get; set; }
public Total total { get; set; }
}
public class User
{
public int user_id { get; set; }
public int total { get; set; }
public int rewards { get; set; }
}
public class Worker
{
public string worker_name { get; set; }
public double rate { get; set; }
public int shares { get; set; }
}
public class Total
{
public int total_user { get; set; }
public int record_date { get; set; }
}
Now you can easily loop through each worker to get one's details like below:
string json = "YOUR_JSON_STRING";
RootObject rootObject = JsonConvert.DeserializeObject<RootObject> ( json );
Console.WriteLine("Total no. of workers: {0}", rootObject.workers.Count);
foreach ( KeyValuePair<string, Worker> worker in rootObject.workers )
{
Console.WriteLine("Name: {0}, Rate: {1}, Shares: {2}", worker.Value.worker_name, worker.Value.rate.ToString("F2", CultureInfo.InvariantCulture), worker.Value.shares);
}