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);
}
Related
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
}
]
I am making a rest API on my exercise, and I have chosen for a very simple approach, I have three entities: Chapter, Theme, Priority. One chapter may have 0 or 1 theme and 0 or 1 priority.
So they are looking like this in JSON format.
CHAPTER:
{
"id": 4,
"title": "De centrale limietstelling",
"isFinished": false,
"priority": {
"id": 1,
"title": "Zeer belangerijk zeker instuderen",
"color": "#F1128D"
},
"theme": {
"id": 1,
"title": "Onderzoekstechnieken"
},
"date": null
}
THEME:
{
"id": 2,
"title": "Ontwerpen 3"
}
PRIORITY:
{
"id": 1,
"title": "Zeer belangerijk zeker instuderen",
"color": "#F1128D"
}
I can delete priority and then in the Chapter the priorities of this id are set to null as expected.
but when i edit any chapter with PUT request and set for example Theme to null:
{
"id": 4,
"title": "De centrale limietstelling",
"isFinished": false,
"priority": null,
"theme": null,
"date": null
}
have a 204 responce.
but when i open these chapter again i see that priority and theme are not set to null, but remain th e same as it was.
to clarify my entities these are the code of chapter, theme and prio:
public class Chapter
{
public int Id { get; set; }
public string Title { get; set; }
public bool IsFinished { get; set; }
public Priority? Priority { get; set; }
public Theme? Theme { get; set; }
public DateTime? Date { get; set; }
public Chapter()
{
IsFinished = false;
}
}
public class Theme
{
public int Id { get; set; }
public string Title { get; set; }
}
public class Priority
{
public int Id { get; set; }
public string Title { get; set; }
public string Color { get; set; }
}
I Also need to make use of DTO:
public class ChapterDTO
{
[Required]
public string Title { get; set; }
public Priority? Priority { get; set; }
public Theme? Theme { get; set; }
[DataType(DataType.Date)]
public DateTime? Date { get; set; }
public ChapterDTO()
{
}
}
public class PriorityDTO
{
[Required]
public string Title { get; set; }
public string Color { get; set; }
}
public class ThemeDTO
{
[Required]
public string Title { get; set; }
}
And this is my mapping to DB
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Chapter>().HasOne(e => e.Priority).WithMany().OnDelete(DeleteBehavior.SetNull).IsRequired(false);
builder.Entity<Chapter>().HasOne(e => e.Theme).WithMany().OnDelete(DeleteBehavior.SetNull).IsRequired(false);
}
how do I make it possible to store the null reference to theme and subject in Chapter?
Kind regard, ilya
So in my angular frontend I am sending this JSON to my backend.
[
{
"AccountingDate": 20171130,
"RegistrationNo": 3951,
"IDKT": "34HS991016",
"OriginalIDKT": "test",
"CounterAccountIDKT": "34HS980876",
"Text": "006-Hest prov-Ytd NOV17",
"ProjectCode": "078",
"Currency": "DKK",
"Balance": 1
},
{
"AccountingDate": 20171130,
"RegistrationNo": 3951,
"IDKT": "34JR991016",
"OriginalIDKT": "test",
"CounterAccountIDKT": "34JR980876",
"Text": "006-Hest prov-Ytd NOV18",
"ProjectCode": "078",
"Currency": "DKK",
"Balance": 1
}
]
My .NET Core controller method looks like the following:
[HttpPost]
public IActionResult Post([FromBody] AccountBookKeeping[] request)
{
return Ok(request);
}
But when debugging the request object will be null. This is my problem.
My AccountBookKeeping model looks like:
using System;
namespace GFSUploadAPI
{
public class AccountBookKeeping
{
public int AccountingDate { get; set; }
public string RegistrationNo { get; set; }
public string Currency { get; set; }
public string IDKT { get; set; }
public string OriginalIDKT { get; set; }
public string CounterAccountIDKT { get; set; }
public string ProjectCode { get; set; }
public float Balance { get; set; }
public string Text { get; set; }
}
}
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; }
}
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);