Map JSON object to C# class property array - c#

JSON
{
"SoftHoldIDs": 444,
"AppliedUsages": [
{
"SoftHoldID": 444,
"UsageYearID": 223232,
"DaysApplied": 0,
"PointsApplied": 1
}
],
"Guests": [
1,
2
]
}
In the above JSON SoftholdIDs is integer and AppliedUsages is class array property in C# Model
Issue is --How we can map JSON to class property.
Class code
public class ReservationDraftRequestDto
{
public int SoftHoldIDs { get; set; }
public int[] Guests { get; set; }
public AppliedUsage[] AppliedUsages { get; set; }
}
public class AppliedUsage
{
public int SoftHoldID { get; set; }
public int UsageYearID { get; set; }
public int DaysApplied { get; set; }
public int PointsApplied { get; set; }
}
Tried below code for mapping
ReservationDraftRequestDto reservationDto = null;
dynamic data = await reservationDraftRequestDto.Content.ReadAsAsync<object>();
reservationDto = JsonConvert.DeserializeObject<ReservationDraftRequestDto>(data.ToString());

You need to change
dynamic data = await reservationDraftRequestDto.Content.ReadAsAsync<object>();
to
string data = await reservationDraftRequestDto.Content.ReadAsStringAsync();
this will read your response as string
then do
reservationDto = JsonConvert.DeserializeObject<ReservationDraftRequestDto>(data);

this work
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
string json = #"{""SoftHoldIDs"": 444,""AppliedUsages"": [ {""SoftHoldID"": 444,""UsageYearID"": 223232,""DaysApplied"": 0,""PointsApplied"": 1}],""Guests"": [ 1, 2]}";
Rootobject reservationDto = JsonConvert.DeserializeObject<Rootobject>(json.ToString());
Debug.WriteLine(reservationDto.SoftHoldIDs);
foreach (var guest in reservationDto.Guests)
{
Debug.WriteLine(guest);
}
}
}
public class Rootobject
{
public int SoftHoldIDs { get; set; }
public Appliedusage[] AppliedUsages { get; set; }
public int[] Guests { get; set; }
}
public class Appliedusage
{
public int SoftHoldID { get; set; }
public int UsageYearID { get; set; }
public int DaysApplied { get; set; }
public int PointsApplied { get; set; }
}
}
First create class copying json as classwith visualstudio.
Next you have double quote in json respons so deal with it.
Json.NET: Deserilization with Double Quotes

Related

Show the request from rest api server with c # on gridview

I'm connecting with c # to rest api server. and a json output comes as below.
WindowsForms, Model and Repository files are as follows.
1-) In other words, I want to transfer the json data incoming "result" object to the model file and show it on the gridview.
2-) Also, when I make a "Get" request, I want to request a "Body" object with a parameter.
example: {"business_code": "dental"}
CustomersModel.cs
namespace HastaTakip.Models
{
public class CustomersModel
{
public result _result { get; set; }
public class result
{
public int id { get; set; }
public string customer_name { get; set; }
public string customer_lastname { get; set; }
public string customer_identity { get; set; }
public string customer_gender { get; set; }
public string customer_phone { get; set; }
public string customer_description { get; set; }
public bool customer_status { get; set; }
public string doctor { get; set; }
public string customer_code { get; set; }
public string business_code { get; set; }
public int user_code_id { get; set; }
}
}
}
CustomersRepository.cs
using System.Net.Http;
using System;
using System.Threading.Tasks;
using HastaTakip.Models;
using Newtonsoft.Json;
namespace HastaTakip.Api
{
public class CustomersRepository
{
public HttpClient _client;
public HttpResponseMessage _response;
public CustomersRepository()
{
_client = new HttpClient();
_client.BaseAddress = new Uri("http://localhost:3000/");
_client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<CustomersModel> GetList()
{
_response = await _client.GetAsync($"customers");
var json = await _response.Content.ReadAsStringAsync();
var listCS = JsonConvert.DeserializeObject<CustomersModel>(json);
return listCS;
}
}
}
WindowsForms.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HastaTakip.Api;
using HastaTakip.Models;
namespace HastaTakip.Forms
{
public partial class frmCustomerList : Form
{
CustomersRepository _repository = new CustomersRepository();
public frmCustomerList()
{
InitializeComponent();
LoadData();
}
private async void LoadData()
{
var listCS = await _repository.GetList();
gridControl1.DataSource = listCS;
}
private void frmCustomerList_Load(object sender, EventArgs e)
{
}
}
}
Json results
{
"result": [
{
"id": 1,
"customer_name": "Test1",
"customer_lastname": null,
"customer_identity": "54sd45",
"customer_gender": "Man",
"customer_phone": null,
"customer_description": "kkjkjk.",
"customer_status": null,
"doctor": null,
"customer_code": "bcc50586-6960-4766-9468-c9dc55780e40",
"business_code": "dental",
"user_code_id": 1
},
{
"id": 2,
"customer_name": "Depron",
"customer_lastname": null,
"customer_identity": "564434",
"customer_gender": "WOMEN",
"customer_phone": null,
"customer_description": "record test.",
"customer_status": null,
"doctor": null,
"customer_code": "344865b4-1028-4051-9ec4-71db17414787",
"business_code": "dental",
"user_code_id": 1
}
]
}
From the json file you should get back a list or an array but in your model you only have one result the correct way would be:
public class CustomersModel
{
public List<result> _result { get; set; }
}
public class result
{
public int id { get; set; }
public string customer_name { get; set; }
public string customer_lastname { get; set; }
public string customer_identity { get; set; }
public string customer_gender { get; set; }
public string customer_phone { get; set; }
public string customer_description { get; set; }
public bool customer_status { get; set; }
public string doctor { get; set; }
public string customer_code { get; set; }
public string business_code { get; set; }
public int user_code_id { get; set; }
}
also i would never use nested classes unless there is a very good reason. and as long as it is not private i don't see a reason here anyway.

convert API response to class object in C# by removing data type from response

I am getting API response something like this
{
"results": [{
"itemdescription": {
"raw": "xyz"
},
"productcategory5": {
"raw": "avx"
},
"productcategory6": {
"raw": "DG"
}
}]
}
I am trying to convert this to class object using DeserializeObject
lObjJsonData = JsonConvert.DeserializeObject<ProductVm>(lObjResponseData);
but in my VM I have to add extra property
[JsonProperty("raw")]
public string raw { get; set; }
How I can avoid this as if I convert my class object to json it will again have datatype property with every field .
my class code is below -
public class ProductAppSearchVm
{
public MetaClass meta { get; set; }
public List<ProductDetails> results { get; set; }
}
public class ProductProperty
{
[JsonProperty("raw")]
public string raw { get; set; }
}
public class ProductDetails
{
public ProductProperty itemdescription{ get; set; }
public ProductProperty productcategory5{ get; set; }
public ProductProperty productcategory6{ get; set; }
}
any suggestion how can I have simple data like -
{
"results": [{
"itemdescription": "xyz"
},
{
"productcategory5": "avx"
},
{
"productcategory6": "DG"
}
]
}
**Not yet sure performance wise. But for your desired output this might give you a hint.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string jsonString = "{\"results\":[{\"itemdescription\":{\"raw\":\"xyz\"},\"productcategory5\":{\"raw\":\"avx\"},\"productcategory6\":{\"raw\":\"DG\"}}]}";
var obj = JsonConvert.DeserializeObject<ProductDetails>(jsonString);
Console.WriteLine(obj.GetFormattedJson);
Console.ReadKey();
}
}
public class ProductDetails
{
[JsonProperty("results")]
public List<Dictionary<string, ProductProperty>> Detail { get; set; }
public string GetFormattedJson
{
get
{
return string.Join(",", Detail.Select(dic => "{\"results\":[" + string.Join(",", dic.Select(pp => $"{{\"{pp.Key}\":\"{pp.Value.Raw}\"}}")) + "]}"));
}
}
}
public class ProductProperty
{
[JsonProperty("raw")]
public string Raw { get; set; }
}
}
Output:

C# - Unexpected character encountered while parsing value: {. Path '[0].Statistics

I am trying to deserialize a JSON object according to my model using the code below:
LoadData<MyModel>(Data.Stats, null);
public void LoadData<TModel>(string data, JsonSerializerSettings jsonSettings) where TModel : class
{
var mockData = JsonConvert.DeserializeObject<Collection<TModel>>(data, jsonSettings); // ERROR HERE
Context.SaveChanges();
}
However I am getting an error that reads
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: {. Path '[0].Statistics', line 7, position 19.'
My JSON object is:
[
{
"Id": 3033,
"Grade": 3,
"Statistics": { //ERROR OCCURS ON THIS PROPERTY
"Avatar.Add": 1,
"TotalPlays": 36,
"Game.TotalPlays.Spell_Mem_Words": 27,
"Book.TotalReads.Count": 23,
"Game.TotalPlays.Count": 39,
"Character.TotalPlays.L": 23,
"Character.TotalPlays.E": 3,
"TotalPlays.Pick_Vocab": 16,
"Character.TotalPlays.R": 22
}
}
]
The Object Model is:
public class MyModel
{
public int Id { get; set; }
public int Grade { get; set; }
public string Statistics { get; set; }
}
Things I Have Tried
(1) Using json lint I have ensured that the json string is valid.
(2) In javascript serializing the object with back ticks surrounding it works. Backticks don't work in C# JS Fiddle
(3) Tried making the Statistics property in object model to use class called stats instead of string like
public class Stats
{
public string Label { get; set;}
public int Value { get; set; }
}
(4) Tried nearly all the answers on this SO post
Unfortunately I still have not solved this issue. Any ideas?
I was able to reproduce the problem with this MCVE:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeserializeJson
{
/**
* REFERENCE:
* https://stackoverflow.com/questions/53562566/
*
* ORIGINAL ERROR:
* "Unexpected character encountered while parsing value: {. Path '[0].Statistics', line 5, position 19."
*/
public class Stats
{
public string Label { get; set; }
public int Value { get; set; }
}
public class MyModel
{
public int Id { get; set; }
public int Grade { get; set; }
public string Statistics { get; set; }
}
class Program
{
static Collection<MyModel> LoadData(string data)
{
var retval = JsonConvert.DeserializeObject<Collection<MyModel>>(data);
return retval;
}
static void Main(string[] args)
{
try
{
string s = File.ReadAllText(#"test-data.json");
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented
};
Collection <MyModel> mockData = Program.LoadData(s);
System.Console.WriteLine("#/items= " + mockData.Count);
foreach (MyModel item in mockData)
{
System.Console.WriteLine(" id= {0}, Grade={1}, Statistics={2}", item.Id, item.Grade, item.Statistics.ToString());
}
}
catch (Exception ex)
{
System.Console.WriteLine("ERROR:", ex);
}
}
}
}
I was able to fix it by:
Elaborating your definition of class Stats, then
Using Stats in the definition of class MyModel:
public class Stats
{
public int AvatarAdd { get; set; }
public int TotalPlays { get; set; }
public int GameTotalPlaysSpellMemWords { get; set; }
public int BookTotalReadsCount { get; set; }
public int GameTotalPlaysCount { get; set; }
public int CharacterTotalPlaysL { get; set; }
public int CharacterTotalPlaysE { get; set; }
public int TotalPlaysPick_Vocab { get; set; }
public int CharacterTotalPlaysR { get; set; }
}
public class MyModel
{
public int Id { get; set; }
public int Grade { get; set; }
public Stats Statistics { get; set; }
}
You have several choices (including use the above example verbatim). My suggestion would be to break "Statistics" down into smaller model classes.
In My case the issue was the JSON File encoding was chosen as "UTF-8-BOM"
I had to convert that to "UTF-8".
Then it worked fine for me.

how can I get json data in to the c# object?

Below is my class for the json output:
class PwdResetRequest
{
public class TopScoringIntent
{
public string intent { get; set; }
public double score { get; set; }
}
public class Intent
{
public string intent { get; set; }
public double score { get; set; }
}
public class Resolution
{
public string value { get; set; }
}
public class Entity
{
public string entity { get; set; }
public string type { get; set; }
public int startIndex { get; set; }
public int endIndex { get; set; }
public Resolution resolution { get; set; }
}
public class RootObject
{
public string query { get; set; }
public TopScoringIntent topScoringIntent { get; set; }
public List<Intent> intents { get; set; }
public List<Entity> entities { get; set; }
}
}
Luis Return result:
{
"query": "create a new password for sjao9841#demo.com",
"topScoringIntent": {
"intent": "ResetLANIDpassword",
"score": 0.9956063
},
"intents": [
{
"intent": "ResetLANIDpassword",
"score": 0.9956063
},
{
"intent": "None",
"score": 0.179328963
}
],
"entities": [
{
"entity": "sjao9841#demo.com",
"type": "builtin.email",
"startIndex": 26,
"endIndex": 47
}
]
}
I have developed the below code for getting the data from the json.
var uri =
"https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/" +
luisAppId + "?" + queryString;
var response = await client.GetAsync(uri);
var strResponseContent = await response.Content.ReadAsStringAsync();
var json = await response.Content.ReadAsStringAsync();
var token = JObject.Parse(json).SelectToken("entities");
foreach (var item in token)
{
var request = item.ToObject<Entity>();
}
// Display the JSON result from LUIS
Console.WriteLine(strResponseContent.ToString());
}
And I only want the data from the "TopScoringIntent". How can I get that using C#? Below is the code that I tried but nothing came out:
Message=Error reading JObject from JsonReader. Path '', line 0, position 0.
Source=Newtonsoft.Json
I may be missing your intent, but if you only care about specific value rather than the entire javascript object, you could do the following.
dynamic json = JsonConvert.Deserialize(data);
var score = json.TopScoringIntent.Score;
That provides the specific value of score within TopScoringIntent. Obviously, you could also build a collection also well, by modifying slightly.
foreach(var point in json.Intents)
Console.WriteLine($"{point[1]} or {point.score}");
I believe that is what you're looking for, to receive a specific value from your object. Please note dynamics are useful, but this approach is a fairly quick and dirty, may not be ideal for your implementation.
quicktype generated the following C# classes and JSON.Net marshaling code for your sample data:
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
// using QuickType;
//
// var pwdResetRequest = PwdResetRequest.FromJson(jsonString);
namespace QuickType
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using J = Newtonsoft.Json.JsonPropertyAttribute;
public partial class PwdResetRequest
{
[J("query")] public string Query { get; set; }
[J("topScoringIntent")] public Ntent TopScoringIntent { get; set; }
[J("intents")] public Ntent[] Intents { get; set; }
[J("entities")] public Entity[] Entities { get; set; }
}
public partial class Entity
{
[J("entity")] public string EntityEntity { get; set; }
[J("type")] public string Type { get; set; }
[J("startIndex")] public long StartIndex { get; set; }
[J("endIndex")] public long EndIndex { get; set; }
}
public partial class Ntent
{
[J("intent")] public string Intent { get; set; }
[J("score")] public double Score { get; set; }
}
public partial class PwdResetRequest
{
public static PwdResetRequest FromJson(string json) => JsonConvert.DeserializeObject<PwdResetRequest>(json, QuickType.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this PwdResetRequest self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
}
internal class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters = {
new IsoDateTimeConverter()
{
DateTimeStyles = DateTimeStyles.AssumeUniversal,
},
},
};
}
}
Now you can use System.Linq to get the maximum Ntent by Score:
var uri = $"https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/${luisAppId}?${queryString}";
var response = await client.GetAsync(uri);
var json = await response.Content.ReadAsStringAsync();
var request = PwdResetRequest.FromJson(json);
var maxIntent = request.Intents.MaxBy(intent => intent.Score);
Here's the generated code in a playground so you can change the type names and other options.

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