json properties as numbers in c# model class? - c#

How can I build a Model class to deserialize a json like this:-
{"query":{"apikey":"65320-2d8b-11eb-864","continent":"Africa"},"data":{"0":{"country_id":1,"name":"Africa","country_code":null,"continent":"Africa"},"9":{"country_id":10,"name":"Algeria","country_code":"dz","continent":"Africa"},"11":{"country_id":12,"name":"Angola","country_code":"ao","continent":"Africa"},"23":{"country_id":24,"name":"Botswana","country_code":"bw","continent":"Africa"},"27":{"country_id":28,"name":"Cameroon","country_code":"cm","continent":"Africa"},"32":{"country_id":33,"name":"Congo","country_code":"cg","continent":"Africa"},"39":{"country_id":40,"name":"Egypt","country_code":"eg","continent":"Africa"},"48":{"country_id":49,"name":"Ghana","country_code":"gh","continent":"Africa"},"62":{"country_id":63,"name":"Ivory Coast","country_code":"ci","continent":"Africa"},"67":{"country_id":68,"name":"Kenya","country_code":"ke","continent":"Africa"},"80":{"country_id":81,"name":"Morocco","country_code":"ma","continent":"Africa"},"85":{"country_id":86,"name":"Nigeria","country_code":"ng","continent":"Africa"},"102":{"country_id":103,"name":"Rwanda","country_code":"rw","continent":"Africa"},"106":{"country_id":107,"name":"Senegal","country_code":"sn","continent":"Africa"},"111":{"country_id":112,"name":"South Africa","country_code":"za","continent":"Africa"},"115":{"country_id":116,"name":"Tanzania","country_code":"tz","continent":"Africa"},"118":{"country_id":119,"name":"Tunisia","country_code":"tn","continent":"Africa"},"120":{"country_id":121,"name":"Uganda","country_code":"ug","continent":"Africa"},"129":{"country_id":130,"name":"Zambia","country_code":"zm","continent":"Africa"},"130":{"country_id":131,"name":"Zimbabwe","country_code":"zw","continent":"Africa"}}}
The problem is in the numbers like "0", "9", "11" etc! How can I convert these numbers to one property in the model class?

If you implement the data item as a Dictionary on your model, these numbers would be the keys of this Dictionary.
public class Model
{
[JsonProperty("query")]
public Query query {get; set; }
[JsonProperty("data")]
public Dictionary<string, Country> Data { get; set; }
}
public class Country
{
[JsonProperty("country_id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("country_code")]
public string Code { get; set; }
[JsonProperty("continent")]
public string Continent { get; set; }
}
public class Query
{
[JsonProperty("apikey")]
public string ApiKey { get; set; }
[JsonProperty("continent")]
public string Continent { get; set; }
}

You can treat these numbers as keys of an dictionary. So may convert them like this:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var testJson = "{\"data\":{\"11\": \"test11\"}}";
var deserialized = (TestClass) JsonConvert.DeserializeObject(testJson, typeof(TestClass));
Console.WriteLine(deserialized.Data[11]);
}
}
public class TestClass
{
public Dictionary<int, string> Data {get;set;}
}
(to test see this dotnetfiddle example)
Obviously only possible if no number appears twice or more.

Related

How to parse JSON dynamic KeyValuePair to C# model in Blazor WASM [duplicate]

I have json that looks like this, the key "123" could be any number.
{
"key1": "",
"key2": {
"items": {
"123": {
"pageid": 123,
"name": "data"
}
}
}
}
I want to deserialize or query the json with System.Text.Json so i can get the value of the key "name". How can I do that with System.Text.Json? I'm using .NET Core 3.1.
Since one of the json keys can vary ("123"), this can be represented by a Dictionary<>. The following classes model your json.
public class ItemProps
{
public int pageid { get; set; }
public string name { get; set; }
}
public class Item
{
public Dictionary<string, ItemProps> items { get; set; }
}
public class Root
{
public string key1 { get; set; }
public Item key2 { get; set; }
}
Then to deserialize using System.Text.Json you would use:
var data = JsonSerializer.Deserialize<Root>(json);
To access name:
var name = data.key2.items["123"].name
Try it online
Note, I named the classes quickly... please consider giving the classes better names, more descriptive names.
Something like:
public class Rootobject
{
public string key1 { get; set; }
public InnerObject key2 { get; set; }
}
public class InnerObject
{
public Dictionary<string, ObjectTheThird> items { get; set; }
= new Dictionary<string, ObjectTheThird>();
}
public class ObjectTheThird
{
public int pageid { get; set; }
public string name { get; set; }
}
and use the APIs on Dictionary<,> to look at the items. Or you just want the first:
var name = obj.key2.items.First().Value.name;

Deserialize JSON to Nested Model

I have a model like below:
public class YourInformationInputModel
{
public YourInformationInputModel()
{
PrimaryBuyerInformation = new PrimaryBuyerInformationInputModel();
}
public PrimaryBuyerInformationInputModel PrimaryBuyerInformation { get; set; }
public bool TermsCondition { get; set; }
}
PrimaryBuyerInputModel like below:
public class PrimaryBuyerInformationInputModel
{
[Required]
public string BuyerFirstName { get; set; }
public string BuyerMiddleInitial { get; set; }
[Required]
public string BuyerLastName { get; set; }
}
and when I am submitting my form then I am getting JSON like below:
{
"PrimaryBuyerInformation.BuyerFirstName": "Sunil",
"PrimaryBuyerInformation.BuyerMiddleInitial": "",
"PrimaryBuyerInformation.BuyerLastName": "Choudhary",
"TermsCondition": "true"
}
When I am trying to deserialize this json the TermsCondition property successfully done, but the property of PrimaryBuyerInformation is not mapped.
var myObject = JsonConvert.DeserializeObject<YourInformationInputModel>(json);
Any idea how to do that ?
Kindly take a cue from the code below, i tested it and you should be able to get your value as request. This solves the issue of you trying to access the property you have mapped in a dot property name format.
Instead your object should be nested in a curly brace showing that the other property belongs to PrimaryBuyerInformationInputModel which is another object entirely.
Best Regards,
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var json = #"{'PrimaryBuyerInformation': {'buyerFirstName': 'Sunil','buyerMiddleInitial': '','buyerLastName': 'Choudhary'},'termsCondition': false}";
var obj = JsonConvert.DeserializeObject<YourInformationInputModel>(json);
Console.WriteLine(obj.PrimaryBuyerInformation.BuyerFirstName);
}
}
public class YourInformationInputModel
{
public YourInformationInputModel()
{
PrimaryBuyerInformation = new PrimaryBuyerInformationInputModel();
}
public PrimaryBuyerInformationInputModel PrimaryBuyerInformation { get; set; }
public bool TermsCondition { get; set; }
}
public class PrimaryBuyerInformationInputModel
{
public string BuyerFirstName { get; set; }
public string BuyerMiddleInitial { get; set; }
public string BuyerLastName { get; set; }
}

Query or deserialize json with dynamic keys using System.Text.Json

I have json that looks like this, the key "123" could be any number.
{
"key1": "",
"key2": {
"items": {
"123": {
"pageid": 123,
"name": "data"
}
}
}
}
I want to deserialize or query the json with System.Text.Json so i can get the value of the key "name". How can I do that with System.Text.Json? I'm using .NET Core 3.1.
Since one of the json keys can vary ("123"), this can be represented by a Dictionary<>. The following classes model your json.
public class ItemProps
{
public int pageid { get; set; }
public string name { get; set; }
}
public class Item
{
public Dictionary<string, ItemProps> items { get; set; }
}
public class Root
{
public string key1 { get; set; }
public Item key2 { get; set; }
}
Then to deserialize using System.Text.Json you would use:
var data = JsonSerializer.Deserialize<Root>(json);
To access name:
var name = data.key2.items["123"].name
Try it online
Note, I named the classes quickly... please consider giving the classes better names, more descriptive names.
Something like:
public class Rootobject
{
public string key1 { get; set; }
public InnerObject key2 { get; set; }
}
public class InnerObject
{
public Dictionary<string, ObjectTheThird> items { get; set; }
= new Dictionary<string, ObjectTheThird>();
}
public class ObjectTheThird
{
public int pageid { get; set; }
public string name { get; set; }
}
and use the APIs on Dictionary<,> to look at the items. Or you just want the first:
var name = obj.key2.items.First().Value.name;

C# JSON Deserialize Dictionary<string, Dictionary<string, string>> optional?

My payload would look something like this:
{
"REFERENCE": "1",
"FIELDS" : {
"CUST" : "1234",
"PROD" : "PR2134",
"LIMIT" : "12345",
"LINES" : {
"LINE" : "01",
"DATA" : "12"
}
}
}
My object simply has the following:
public class TriggerRequest
{
public string reference { get; set; }
public Dictionary<string, string> fields { get; set; }
}
Obviously, this doesn't handle the LINES object. How can I create a class that deserializes an inbound payload where something like LINES is dynamic (i.e. I can send in any Dictionary> at any point in the payload and it'll deserialize correctly. Is this something when I need to create a custom JsonConverter?
You could use dynamic instead.
public class TriggerRequest
{
public string reference { get; set; }
public dynamic fields { get; set; }
}
This should allow you to access (string)request.fields.lines.data directly in your code, for example.
However, if you don't know at compile time what values will be in there, you may prefer to make fields a JObject.
public class TriggerRequest
{
public string reference { get; set; }
public JObject fields { get; set; }
}
This gives you the opportunity to write code that inspects what kind of data is in each of its properties and respond accordingly.
Finally, if you do know what properties you expect fields to have, create a separate class for it.
public class TriggerRequest
{
public string reference { get; set; }
public TriggerRequestFields fields { get; set; }
}
public class TriggerRequestFields
{
public string cust {get;set;}
...
public TriggerRequestLines lines {get;set;}
}
public class TriggerRequestLines
{
public string line {get;set;}
public string data {get;set;}
}
Try changing
public Dictionary<string, dynamic> fields { get; set; }
With
public Dictionary<string, object> fields { get; set; }

Convert JSON Object to C# Object

I have a json object and I am trying to convert it to my c# object. Here is my JSON:
{"GuvenlikNoktaArray": {"GuvenlikNoktası": [{"Id": 1,"GuvenlikNoktası1":"SANTIYE","KartNo":"000001889174217","Sira": 1},{"Id": 2,"GuvenlikNoktası1":"INSAAT","KartNo":"000000803567858","Sira": 2},{"Id": 3,"GuvenlikNoktası1":"ÇALISMA","KartNo":"000003417926233","Sira": 3},{"Id": 4,"GuvenlikNoktası1":"GÜVENLIK","KartNo":"000001888909897","Sira": 4}]}}
And my c# class:
public partial class GuvenlikNoktası
{
public GuvenlikNoktası()
{
this.GüvenlikNoktasıOlay = new HashSet<GüvenlikNoktasıOlay>();
this.PanikButonuAlarmlari = new HashSet<PanikButonuAlarmlari>();
}
public int Id { get; set; }
public string GuvenlikNoktası1 { get; set; }
public string KartNo { get; set; }
public string Sira { get; set; }
public virtual ICollection<GüvenlikNoktasıOlay> GüvenlikNoktasıOlay { get; set; }
public virtual ICollection<PanikButonuAlarmlari> PanikButonuAlarmlari { get; set; }
}
And last, my convert try:
public void AddIstasyon(string json_string)
{
GuvenlikNoktası result = new JavaScriptSerializer().Deserialize<GuvenlikNoktası>(json_string);
}
I don't get any errors but when I debuged, I see that all attributes inside 'result' are null. It seems like an empty object. How can I get a correct 'GuvenlikNoktası' object ? (Btw I am pretty sure I am getting the json object correctly).
If you must keep this JSON structure as-is you may use JObject to navigate inside your JSON properties until you reach your target objects to deserizlize. Please can you try the code below;
PS: This code uses Newtonsoft.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SO_39847703
{
class Program
{
static void Main(string[] args)
{
string json = "{\"GuvenlikNoktaArray\": {\"GuvenlikNoktası\": [{\"Id\": 1,\"GuvenlikNoktası1\":\"SANTIYE\",\"KartNo\":\"000001889174217\",\"Sira\": 1},{\"Id\": 2,\"GuvenlikNoktası1\":\"INSAAT\",\"KartNo\":\"000000803567858\",\"Sira\": 2},{\"Id\": 3,\"GuvenlikNoktası1\":\"ÇALISMA\",\"KartNo\":\"000003417926233\",\"Sira\": 3},{\"Id\": 4,\"GuvenlikNoktası1\":\"GÜVENLIK\",\"KartNo\":\"000001888909897\",\"Sira\": 4}]}}";
AddIstasyon(json);
}
public static void AddIstasyon(string json_string)
{
dynamic jsonObject = JObject.Parse(json_string);
string jsonToDeserializeStrongType = jsonObject["GuvenlikNoktaArray"]["GuvenlikNoktası"].ToString();
List<GuvenlikNoktası> result = JsonConvert.DeserializeObject<List<GuvenlikNoktası>>(jsonToDeserializeStrongType); ;
}
}
public partial class GuvenlikNoktası
{
public GuvenlikNoktası()
{
this.GüvenlikNoktasıOlay = new HashSet<GüvenlikNoktasıOlay>();
this.PanikButonuAlarmlari = new HashSet<PanikButonuAlarmlari>();
}
public int Id { get; set; }
public string GuvenlikNoktası1 { get; set; }
public string KartNo { get; set; }
public string Sira { get; set; }
public virtual ICollection<GüvenlikNoktasıOlay> GüvenlikNoktasıOlay { get; set; }
public virtual ICollection<PanikButonuAlarmlari> PanikButonuAlarmlari { get; set; }
}
public class GüvenlikNoktasıOlay
{
}
public class PanikButonuAlarmlari
{
}
}
Hope this helps
Your JSON data and your class definition do not fit together. Therefore the default values (NULL) are provided by the serializer.
In order to deserialize the given JSON data you need a class structure like:
public class Root
{
public LevelOne GuvenlikNoktaArray {get; set;}
}
public class LevelOne {
public IEnumerable<GuvenlikNoktası> GuvenlikNoktası {get; set;}
}
You can use this class.
public class GuvenlikNoktası
{
public int Id { get; set; }
public string GuvenlikNoktası1 { get; set; }
public string KartNo { get; set; }
public int Sira { get; set; }
}
public class GuvenlikNoktaArray
{
public IList<GuvenlikNoktası> GuvenlikNoktası { get; set; }
}
public class Example
{
public GuvenlikNoktaArray GuvenlikNoktaArray { get; set; }
}
You can use this link For your referencehttp://jsonutils.com/.

Categories

Resources