C# Newtonsoft.Json Convert type - c#

I have to:
DeserializeObject - do some changes - SerializeObject
When my Json have miltiple types e.g.
{
"type": "test",
"currentStatus": "Active",
"id": "987",
"items": [
{
"type": "test1",
"id": "123",
"name": "Segment Members",
"memberCount": "0",
"outputTerminals": [
{
"type": "test2",
"id": "123",
"connectedId": "123",
"terminalType": "out"
}
],
"position": {
"type": "Position",
"x": "46",
"y": "14"
},
"isFinished": "true",
"isRecurring": "false",
"segmentId": "123"
},
{
"type": "test5",
"id": "1390",
"name": "Yay! Clickers",
"memberCount": "2",
"position": {
"type": "Position",
"x": "330",
"y": "375"
},
"waitFor": "2592000"
},
{
"type": "test3",
"id": "1391",
"name": "test",
"memberCount": "73",
"outputTerminals": [
{
"type": "test4",
"id": "123",
"connectedId": "123",
"connectedType": "CampaignWaitAction",
"terminalType": "yes"
},
{
"type": "test4",
"id": "123",
"connectedId": "123",
"connectedType": "CampaignWaitAction",
"terminalType": "no"
}
],
"position": {
"type": "Position",
"x": "123",
"y": "123"
},
"testId": "123"
}
]
}
What data type i should use for this operation? dynamic, object, Jobject...? or maybe something else?

I would just create an object and deseriablize it to that type. A lot easier than doing it dynamically. (assuming it will stay in that structure always)
WHAT TO DO
Copy your Json:
`Edit` -> `Paste Special` -> `Paste JSON As CLASSES`
And there you go! You have the Type you want to deserialize to.
var deserializedJson = JsonConvert.DeserializeObject<YourNewObject>(jsonString);
Note: if the pasting of the json class doesn't work, make sure your json is valid: ClickHereToValidateJson

using Newtonsoft.Json;
dynamic collection = new
{
MultipleType = //call function which returns json here
};
//serialize
var jsonSerializedFeed = JsonConvert.SerializeObject(MultipleType);
//deserialize
var jsonSerializedFeed = JsonConvert.DeserializeObject(MultipleType);
Hope it helps

You can create classes and serialize/deserialize json:
public class OutputTerminal
{
public string type { get; set; }
public string id { get; set; }
public string connectedId { get; set; }
public string terminalType { get; set; }
public string connectedType { get; set; }
}
public class Position
{
public string type { get; set; }
public string x { get; set; }
public string y { get; set; }
}
public class Item
{
public string type { get; set; }
public string id { get; set; }
public string name { get; set; }
public string memberCount { get; set; }
public IList<OutputTerminal> outputTerminals { get; set; }
public Position position { get; set; }
public string isFinished { get; set; }
public string isRecurring { get; set; }
public string segmentId { get; set; }
public string waitFor { get; set; }
public string testId { get; set; }
}
public class Root
{
public string type { get; set; }
public string currentStatus { get; set; }
public string id { get; set; }
public IList<Item> items { get; set; }
}
And then:
string json = JsonConvert.SerializeObject(rootObject);
Root root = JsonConvert.DeserializeObject<Root>(json);
Also, you can use dynamic type without classes:
string json = JsonConvert.SerializeObject(dynamicObject);
dynamic obj = JsonConvert.DeserializeObject(json);

Related

C# DeserializeObject change class attribute name

Hello I have one json text one attribute includes $type. I want to change it to type in my response but it is again written as $type.
public class DocumentDTO
{
public string Version { get; set; }
public List<DocumentInfo> Documents { get; set; }
}
public class DocumentInfo
{
public string DocumentState { get; set; }
public DocumentData DocumentData { get; set; }
public string DocumentAsBase64 { get; set; }
}
public class DocumentData
{
public string Name { get; set; }
[JsonProperty(PropertyName = "$type")]
public string type { get; set; }
public List<DocumentField> Fields { get; set; }
}
public class DocumentField
{
public string Name { get; set; }
[JsonProperty(PropertyName = "$type")]
public string type { get; set; }
public string SuspiciousSymbols { get; set; }
public string RecognizedValue { get; set; }
public string Value { get; set; }
}
I am deserializing like below code
DocumentDTO documentResult = JsonConvert.DeserializeObject<DocumentDTO>(jsonText);
In my api response it is still as $type even I want type. What is my missing here?
Below one is not my want
{
"message": null,
"hasError": false,
"errors": [],
"data": [
{
"version": "1.1",
"documents": [
{
"documentState": "Correct",
"documentData": {
"name": "OthersTWN",
"$type": "Document",
"fields": [
{
"name": "DocumentGUID",
"$type": "Text",
"suspiciousSymbols": null,
"recognizedValue": null,
"value": ""
}
]
},
"documentAsBase64": ""
}
]
}
],
"percentage": 100
}
Below one is my want
{
"message": null,
"hasError": false,
"errors": [],
"data": [
{
"version": "1.1",
"documents": [
{
"documentState": "Correct",
"documentData": {
"name": "OthersTWN",
"type": "Document",
"fields": [
{
"name": "DocumentGUID",
"type": "Text",
"suspiciousSymbols": null,
"recognizedValue": null,
"value": ""
}
]
},
"documentAsBase64": ""
}
]
}
],
"percentage": 100
}
Thanks in advance

Method to map data from two JSON Files

Can you give me an example how to write a method in c# to map products from a Json file and match the group name by productId from a different file? I just want to output the results to look something like this
{
"Category": "Shoes",
"AsOfDate": "12/02/2021",
"Quotes": [
{
"ProductId": "Shoe 1",
"AsOfDate": "12/02/2021",
"Value": 11481.99
},
{
"ProductId": "Shoe 2",
"AsOfDate": "12/02/2021",
"Value": 5534.99
},
{
"ProductId": "Shoe 3",
"AsOfDate": "12/02/2021",
"Value": 4753.99
}]
}
[Name("ProductId")]
public string ProductId { get; set; }
[Name("Date")]
public DateTime Date { get; set; }
[Name("Price")]
public decimal Price { get; set; }
public string Category { get; set; }
public string ProductId { get; set; }
public IEnumerable<QuotesModel> Quotes { get; set; }
Add the following model to your project
public class Rootobject
{
public string Category { get; set; }
public string AsOfDate { get; set; }
public Quote[] Quotes { get; set; }
}
public class Quote
{
public string ProductId { get; set; }
public string AsOfDate { get; set; }
public float Value { get; set; }
}
then you could deserialize your JSON file like this
string jsonString = File.ReadAllText("fileName.tex");
Rootobject rootobject = JsonSerializer.Deserialize<Rootobject>(jsonString);
don't forget, use this name spaces
using System.Text.Json;
using System.IO;
Read more on How to serialize and deserialize JSON in .NET
Product Json is like
[
{
"ProductId": "EU9012 Curncy",
"AsOfDate": "2019-12-31T00:00:00",
"Value": 4741.99
},
{
"ProductId": "EU2026 Govt",
"AsOfDate": "2019-12-31T00:00:00",
"Value": 1432.99
},
{
"ProductId": "EU2020 Curncy",
"AsOfDate": "2019-12-31T00:00:00",
"Value": 4356.99
},
]
And Category Json looks like
[
{
"GroupName": "Shoes",
"ProductId": "EUCF101",
"Quotes": null
},
{
"GroupName": "Tshirts",
"ProductId": "EUCF1010",
"Quotes": null
},
{
"GroupName": "Jeans",
"ProductId": "EUCF1012",
"Quotes": null
},
]
And i need a method to create a single json to output quotes for each category based on productId match

Deserialize Json to C# object with array of arrays

Hello I have serious issues with populating my JSON file to C# object, because JSON contains "array of arrays of arrays". I need to create class with all the arrays to be able load the files there after deserialize, but i have no idea how to create structure like that.
JSON file:
{
"status": true,
"result": [
{
"ID": "1",
"UserID": "1001",
"web_id": "2753",
"certificate_id": "31",
"domain": "testsomething.com",
"status": "ssl_uninstalling",
"updated_at": "2017-02-15 15:08:04",
"IP": "xx.x.xxx.xxx",
"OS_version": "CentOS release 4.8"
},
{
"ID": "2",
"UserID": "1001",
"web_id": "2753",
"certificate_id": "31",
"domain": "admin.testsomething.com",
"status": "ssl_uninstalling",
"updated_at": "2017-02-13 14:19:45",
"IP": "xx.x.xxx.xxx",
"OS_version": "CentOS release 4.8"
},
{
"ID": "3",
"UserID": "1001",
"web_id": "2753",
"certificate_id": "31",
"domain": "www.testsomething16.com",
"status": "ssl_uninstalling",
"updated_at": "2017-02-16 16:22:40",
"IP": "xx.x.xxx.xxx",
"OS_version": "CentOS release 4.8"
},
{
"ID": "4",
"UserID": "1001",
"web_id": "2753",
"certificate_id": "31",
"domain": "blog.testsomething.com",
"status": "ssl_uninstalling",
"updated_at": "2017-02-16 16:22:40",
"IP": "xx.x.xxx.xxx",
"OS_version": "CentOS release 4.8"
}
],
"errors": []
}
The structure for your json might look like
public class Result
{
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("UserID")]
public string UserID { get; set; }
[JsonProperty("web_id")]
public string web_id { get; set; }
[JsonProperty("certificate_id")]
public string certificate_id { get; set; }
[JsonProperty("domain")]
public string domain { get; set; }
[JsonProperty("status")]
public string status { get; set; }
[JsonProperty("updated_at")]
public string updated_at { get; set; }
[JsonProperty("IP")]
public string IP { get; set; }
[JsonProperty("OS_version")]
public string OS_version { get; set; }
}
public class Rootobject
{
[JsonProperty("status")]
public bool status { get; set; }
[JsonProperty("result")]
public List<Result> result { get; set; }
[JsonProperty("errors")]
public List<object> errors { get; set; }
}
You can use Visual Studio to create classes for you out of JSON.
Copy your JSON in the clipboard. that means just CTRL + C and then go to Visual Studio Edit -> Paste Special -> Paste JSON As Classes
Another way out to create class sturcture for your JSON could be you can go to json2csharp: generate c# classes from json and create the classes.
I think you can create a model like below:
public class Example
{
public bool Status { get; set; }
public ResultModel ResultModel { get; set; }
public bool Error { get; set; }
public Example()
{
ResultModel = new ResultModel();
}
}
public class ResultModel
{
public int ID { get; set; }
public int UserId { get; set; }
public int WebId { get; set; }
}

JSON data mapping with C# class models

I have a noSQL database. When I'm trying to map the JSON data with C# class models, some of my data get mapped, but some don't.
Below is my Sample JSON format.
{
"J1D0GhKmzAT4gRn5VkfPKKVCfku2": {
"reports": {
"-KYbi7tbJoZJmCs8hcHy": {
"age": "0",
"description": "Test",
"incident": "Test",
"location": "Test"
},
"-KYbmoWJwzSSS0llsSZN": {
"age": "0",
"description": "Test",
"incident": "Test",
"location": "Test"
},
"-KYbszjzkYnH2N9xbFMJ": {
"age": "0",
"description": "Test",
"incident": "Test",
"location": "Test"
}
},
"user_info": {
"dob": "Feb 11, 2016",
"name": "Test",
"phone": "44444",
"sex": "Male",
"work": "llllll"
}
},
"JxmpIWWioFbg1Po4gXtV07pwDvX2": {
"reports": {
"-KYiiDRl7fYAPdav13h3": {
"age": "0",
"description": "Test",
"incident": "Test",
"location": "Test"
},
"-KYinWZeP7N24x8QUC6O": {
"age": "0",
"description": "Test",
"incident": "Test",
"location": "Test"
}
},
"user_info": {
"dob": "Feb 11, 2016",
"name": "Test",
"phone": "44444",
"sex": "Male",
"work": "llllll"
}
}
}
and My C# Class Models are as below
public class User
{
public user_info user_info { get; set; }
public reports reports { get; set; }
}
public class user_info
{
public string dob { get; set; }
public string name { get; set; }
public string phone { get; set; }
public string sex { get; set; }
public string work { get; set; }
}
public class reports
{
public List<reportInfo> reportInfo { get; set; }
}
public class reportInfo
{
public string age { get; set; }
public string description { get; set; }
public string incident { get; set; }
public string location { get; set; }
}
Here, when I try to map the JSON with C# classes, only the user_info model gets populated for some reason. There is a matching property in JSON. But my reports model doesn't get populated, because it has some dynamic properties which is not getting mapped with model.
Please let me know where I am going wrong and the possible solution.
Thanks in advance.
Following dbc advice, you should modify your model.
Delete the reports class and modify User class like this:
public class User
{
public user_info user_info { get; set; }
public Dictionary<string, reportInfo> reports { get; set; }
}

json deserialize returns null value for elements c#

here is my json response that I am trying to deserialize
[{
"Musician": {
"id": "554343",
"Name": "16408",
"Age": "22"
},
"Albums": [{
"id": "34343",
"AlbumName": "Super charge",
"ReleaseDate": "",
"Hits": ""
}, {
"id": "34222",
"AlbumName": "Super 2",
"ReleaseDate": "",
"Hits": ""
}]
},
{
"Musician": {
"id": "554344",
"Name": "16468",
"Age": "32"
},
"Albums": [{
"id": "34323",
"AlbumName": "Awesome one",
"ReleaseDate": "",
"Hits": ""
}, {
"id": "34222",
"AlbumName": "Awesome two",
"ReleaseDate": "",
"Hits": ""
}]
}]
here are my class
public class Musician
{
public string id { get; set; }
public string Name { get; set; }
public string Age { get; set; }
}
public class Album
{
public string id { get; set; }
public string AlbumName { get; set; }
public string ReleaseDate { get; set; }
public string Hits { get; set; }
}
public class RootObject
{
public Musician Musician { get; set; }
public List<Album> Albums { get; set; }
}
this is the code i am using to deserialize objects
var musicians = JsonConvert.DeserializeObject<List<Musician>>(data);
var album = JsonConvert.DeserializeObject<List<Album>>(data);
musicians variable shows 2 counts of record while debugging but value of elements id,Name,Age always shows null. Not able to recognize what exactly causing it.
You should be deserializing as collection of RootObjects.
var musicians = JsonConvert.DeserializeObject<IEnumerable<RootObject>>(data);
Output

Categories

Resources