Got the following structure given:
public class TaskList
{
public string Name { get; set; }
public List<ToDoTask> ToDoTasks { get; set; }
}
public class ToDoTask
{
public string Name { get; set; }
public string Note { get; set; }
public DateTime LastEdit { get; set; }
public bool Finished { get; set; }
}
I'm using System.Text.Json in .NET 5.0 to serialize a List successfully into a json-file:
JsonSerializerOptions serializeOptions = new() { WriteIndented = true };
string json = JsonSerializer.Serialize(taskLists, serializeOptions);
the result looks fine:
{
"TaskLists": [
{
"Name": "List1",
"ToDoTasks": [
{
"Name": "Task1",
"Note": "",
"LastEdit": "2022-04-19T13:05:10.0415588+02:00",
"Finished": false
},
{
"Name": "Task2",
"Note": "",
"LastEdit": "2022-04-19T13:05:13.9269202+02:00",
"Finished": false
}
]
},
{
"Name": "List2",
"ToDoTasks": [
{
"Name": "Task3",
"Note": "",
"LastEdit": "2022-04-19T13:05:18.3989081+02:00",
"Finished": false
},
{
"Name": "Task4",
"Note": "",
"LastEdit": "2022-04-19T13:05:23.0949034+02:00",
"Finished": false
}
]
}
]
}
When I deserialize this json-file, I only got the TaskLists but the ToDoTasks, are empty.
List<TaskList> taskLists = JsonSerializer.Deserialize<List<TaskList>>(json);
What do I have to do, get also the ToDoTask-Childs included into the deserialized objects?
Whenever you cannot figure out your model class, you can use Visual Studio's Edit - Paste Special - Paste JSON as Class to check out.
Your model classes should be like this:
public class Rootobject
{
public Tasklist[] TaskLists { get; set; }
}
public class Tasklist
{
public string Name { get; set; }
public Todotask[] ToDoTasks { get; set; }
}
public class Todotask
{
public string Name { get; set; }
public string Note { get; set; }
public DateTime LastEdit { get; set; }
public bool Finished { get; set; }
}
And you can Deserialize it:
static void Main(string[] args)
{
var query = JsonSerializer.Deserialize<Rootobject>(File.ReadAllText("data.json"));
}
Your json has a root object containing the task list, so List<TaskList> does not represent it correctly. Try:
public class Root
{
public List<TaskList> TaskLists { get; set; }
}
var root = JsonSerializer.Deserialize<Root>(json);
Related
I want to convert the following json string to a C# class. But i cant figure it out... even with a online converter programm like "json2csharp".
{[
{
"tmcp_post_fields": [],
"product_id": 703,
"per_product_pricing": true,
"cpf_product_price": "45",
"variation_id": false,
"form_prefix": "",
"tc_added_in_currency": "EUR",
"tc_default_currency": "EUR"
}
]}
Can someone help me?
I tried these false variations:
public class myclass
{
public List<object> tmcp_post_fields { get; set; }
public int product_id { get; set; }
public bool per_product_pricing { get; set; }
public string cpf_product_price { get; set; }
public bool variation_id { get; set; }
public string form_prefix { get; set; }
public string tc_added_in_currency { get; set; }
public string tc_default_currency { get; set; }
}
or a List of this class
List<myclass>
I use this code to convert it
if (value != null && value.GetType().FullName.StartsWith("Newtonsoft.Json"))
{
string s = value.GetType().FullName;
if (value.GetType().FullName.EndsWith("JArray"))
{
JArray ja = (JArray)Convert.ChangeType(value, typeof(JArray));
if (ja.HasValues)
{
try
{
return ja.ToObject<myclass>(); //this
return ja.ToObject<List<myclass>>(); //or this does NOT work for me
}
catch { }
return value;
}
else
return null;
}
I allway got this error:
Newtonsoft.Json.JsonReaderException - Error reading string. Unexpected
token
If I remove the first opening and closing {} it would work.
your json is not valid, it has extra {} on the sides. Try this
var json=...your json
json=json.Substring(1,json.Length-2);
var jsonDeserialized = JsonConvert.DeserializeObject<Data[]>(json);
and class
public class Data
{
public List<object> tmcp_post_fields { get; set; }
public int product_id { get; set; }
public bool per_product_pricing { get; set; }
public string cpf_product_price { get; set; }
public bool variation_id { get; set; }
public string form_prefix { get; set; }
public string tc_added_in_currency { get; set; }
public string tc_default_currency { get; set; }
}
Another option is to use insert string. This option is even better since you can use parse json string as well.
json=json.Insert(1,"result:");
var jsonDeserialized = JsonConvert.DeserializeObject<Root>(json);
and class
public class Root
{
public Data[] result {get; set;}
}
output
{
"result": [
{
"tmcp_post_fields": [],
"product_id": 703,
"per_product_pricing": true,
"cpf_product_price": "45",
"variation_id": false,
"form_prefix": "",
"tc_added_in_currency": "EUR",
"tc_default_currency": "EUR"
}
]
}
I have the following json
{
"android_play_store_link": "xyz",
"ios_app_store_link": "",
"sticker_packs": [
{
"identifier": "1",
"name": "abc",
"publisher": "Jane Doe",
"tray_image_file": "xyz.png",
"image_data_version":"1",
"avoid_cache":false,
"publisher_email":"",
"publisher_website": "",
"privacy_policy_website": "",
"license_agreement_website": "",
"stickers": [
{
"image_file": "abc.webp",
"emojis": ["☕","🙂"]
},
{
"image_file": "cdf.webp",
"emojis": ["😩","😰"]
},
{
"image_file": "efg.webp",
"emojis": ["☕","🙂"]
}
]
}
]
}
I have no acquaintance with json until now, How can i deserialize this ?
I know how to do the basic read and write code from persistent data path of unity. But how do i process this json ?
My main goal is as the player wins a level, a new key and value would be added to the "stickers" attribute, Also after some levels I want to add changes to the sticker packs attribute later.
Plus how will i modify the value of image data version in a specific sticker pack item ?
Thanks in advance
you can use Newtonsoft.Json library to deserialize and serialize. Find below the respective C# class.
public class Sticker
{
public string image_file { get; set; }
public IList<string> emojis { get; set; }
}
public class StickerPack
{
public string identifier { get; set; }
public string name { get; set; }
public string publisher { get; set; }
public string tray_image_file { get; set; }
public string image_data_version { get; set; }
public bool avoid_cache { get; set; }
public string publisher_email { get; set; }
public string publisher_website { get; set; }
public string privacy_policy_website { get; set; }
public string license_agreement_website { get; set; }
public IList<Sticker> stickers { get; set; }
}
public class Root
{
public string android_play_store_link { get; set; }
public string ios_app_store_link { get; set; }
public IList<StickerPack> sticker_packs { get; set; }
}
Code to Deserialize:
Root root = JsonConvert.DeserializeObject<Root>(json);
I know people asked and already got some answers very similar question before like this, but still, I couldn't figure it out about mine. I have a JSON file contains a multidimensional object, like below:
{
"Common": {
"Required": "Required Entry ",
"Photos": "Photos",
"Videos": "Videos",
"Register": "Register"
},
"Forms": {
"Form": "Forms",
"Name": "Name",
"Phone": "Phone",
"Email": "Email",
"Message": "Message"
},
"Sections": {
"Home": {
"EventDateTime": "",
"MainTitle": "",
"SubTitle": ""
},
"About": {},
"Venue": {},
"Schedule": {},
"Speakers": {},
"Sponsors": {},
"Price": {},
"Contact": {}
}
}
I would like to deserialize it into my view model (LanguagesViewModel) like this:
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class LanguagesViewModel
{
public Common Common { get; set; }
public Buttons Buttons { get; set; }
public Forms Forms { get; set; }
public Navbar Navbar { get; set; }
public Sections Sections { get; set; }
}
public class Common
{
public string Required { get; set; }
public string Photos { get; set; }
public string Videos { get; set; }
public string Register { get; set; }
}
public class Forms
{
public string Form { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Message { get; set; }
}
public class Sections
{
public Home Home { get; set; }
public About About { get; set; }
public Venue Venue { get; set; }
public Schedule Schedule { get; set; }
public Speakers Speakers { get; set; }
public Sponsors Sponsors { get; set; }
public Price Price { get; set; }
public Contact Contact { get; set; }
}
public class Home
{
public string EventDateTime { get; set; }
public string MainTitle { get; set; }
public string SubTitle { get; set; }
}
public class About
{
}
public class Venue
{
}
public class Schedule
{
}
public class Speakers
{
}
public class Sponsors
{
}
public class Price
{
}
public class Contact
{
}
}
Some of the snippet to do this:
using (StreamReader sr = new StreamReader(language_file_path))
{
string contents = sr.ReadToEnd();
items = JsonConvert.DeserializeObject<LanguagesViewModel>(contents);
}
Somehow, I only can get the first level of the objects, which is:
LanguagesViewModel{
Common:null,
Forms:null,
Sections:null
}
Not the second level, not the third level. Did I do something wrong or have I missed something? Very appreciated for any kind of help.
Thank you.
You can Use this static class
public static class JsonHelper
{
public static T ToObject<T>(this string content)
{
var obj = JObject.Parse(content).GetValue(typeof(T).Name);
if (obj == null)
throw new NullReferenceException();
else
return obj.ToObject<T>();
//This ToObject here is default method written in object
}
}
Usage
var mymodel= json.ToObject<Forms>();
Or create a JSON object and read it with magic strings.
//Creating your JSON object
JObject content = JObject.Parse(sr.ReadToEnd()//or your json);
//content["your object name"] let you access to you object
var common =(Common)content["Common"];
in multidimensional objects, you can access them like this.
//content["level1"]["level2"]["level3"] & ...
var sections= (Home)content["Sections"]["Home"];
Also this way may work but i prefer the way with magic strings.
dynamic jsonObject = new JObject.Parse(sr.ReadToEnd());
var common = jsonObject.Common;
You can find more in this link
I hope this Helps!
I'm using Newtonsoft to deserialize JSON data to an object.
My JSON looks like this:
{
"id": "4aa50d01-41bd-45e3-803e-f479a948acf1",
"referenceNumber": "120064",
"status": "Application in Progress",
"borrowers": [
{
"name": "John Doe",
"type": "BORROWER"
},
{
"name": "Jane Doe",
"type": "COBORROWER"
}
],
"propertyAddress": {
"zipCodePlusFour": ""
}
}
The borrowers array can have up to 2 items. 1 with type == "BORROWER"and the other with type == "COBORROWER"
I have a LoanItem class I am deserializing to.
public class LoanItem
{
public string referenceNumber { get; set; }
public string status { get; set; }
}
I know I can mark the LoanItem property with the JSONProperty attribute but I'm wondering if there is a way I can add an array sub item with a condition.
Something maybe like
[JSONProperty("borrowers[WHERE type = 'BORROWER'].name")]
public string BorrowerName { get; set; }
[JSONProperty("borrowers[WHERE type = 'COBORROWER'].name")]
public string CoBorrowerName { get; set; }
Is this possible? Can I use the JSONProperty attribute?
Create a new class Borrower
public class Borrower
{
string Name { get; set; }
string Type { get; set; }
}
Update your LoanItem class to this
public class LoanItem
{
public string referenceNumber { get; set; }
public string status { get; set; }
public List<Borrower> Borrowers {get;set;}
public string BorrowerName { get { return Borrowers.Where(x=>x.Type == "BORROWER").FirstOrDefault().Name; }
public string CoBorrowerName { get { return return Borrowers.Where(x=>x.Type == "COBORROWER").FirstOrDefault().Name; } }
}
Now you can access the BorrowerName and CoborrowerName
I have a json schema and I need to convert it to a C# object or at least into json string.
is there any way to do it by code or by using some tool?
for the Json I'm currently using Json.net.
this is one of my schema:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "UserGroupWsDTO",
"type": "object",
"properties":
{
"members":
{
"type": "array",
"items":
{
"type": "object",
"properties":
{
"uid":
{
"type": "string"
}
}
}
},
"uid":
{
"type": "string"
},
"name":
{
"type": "string"
}
}
}
I need this to create an Object for deserialize the json
EDIT
My Json schema version is 4 and JSON Schema to POCO doesn't support it
Have a look at JSON Schema to POCO which supports v3 JSON.
If you are just "browsing" key-values, then you don't need any extra libs...
just do:
var obj = (JObject)JsonConvert.DeserializeObject(json);
var dict = obj.First.First.Children().Cast<JProperty>()
.ToDictionary(p => p.Name, p =>p.Value);
var dt = (string)dict["title"];
but if instead you need an object of the string, then define a class and deserialize the string to that class... follow this example:
1st define the classes:
public class Uid
{
public string type { get; set; }
}
public class Properties2
{
public Uid uid { get; set; }
}
public class Items
{
public string type { get; set; }
public Properties2 properties { get; set; }
}
public class Members
{
public string type { get; set; }
public Items items { get; set; }
}
public class Uid2
{
public string type { get; set; }
}
public class Name
{
public string type { get; set; }
}
public class Properties
{
public Members members { get; set; }
public Uid2 uid { get; set; }
public Name name { get; set; }
}
public class RootObject
{
public string __invalid_name__$schema { get; set; }
public string title { get; set; }
public string type { get; set; }
public Properties properties { get; set; }
}
and this is the implementation:
string json = #"{...use your json string here }";
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(root.title);
// UserGroupWsDTO