Deserializing JSON into C# Class with dynamic object [duplicate] - c#

This question already has answers here:
Complicated Json to C# Object Deserialize with classes
(2 answers)
Closed 7 months ago.
I have json being returned from an API. The JSON is formatted as below:
{
"success":true,
"code":200,
"total":2,
"data":{
"1019588":{
"name":"(t) Bob Jones",
"calls":213,
"user_id":"1019588"
},
"1019741":{
"name":"(t) Chris Smith",
"calls":387,
"user_id":"1019741"
}
}
}
I am trying to deserialize into a C# class but I am having issues with the dynamic id for each employee row.
My code:
AgentPeformanceResponse viewModel = JsonSerializer.Deserialize<AgentPeformanceResponse>(result.Result);
public class AgentPeformanceResponse
{
public bool success { get; set; }
public int code { get; set; }
public int total { get; set; }
public Data data { get; set; }
public AgentPeformanceResponse()
{
data = new Data();
}
}
public class Data
{
public Data()
{
PerformanceReponse = new List<PerformanceReponse>();
}
public List<PerformanceReponse> PerformanceReponse { get; set; }
}
public class PerformanceReponse
{
public string name { get; set; }
public int calls { get; set; }
public string user_id { get; set; }
}
How do I handle the dynamic employee ID so that I can deserialize it all into one object?

You should use a Dictionary:
public class AgentPeformanceResponse
{
public bool success { get; set; }
public int code { get; set; }
public int total { get; set; }
public Dictionary<string,PerformanceReponse> data { get; set; }
}
public class PerformanceReponse
{
public string name { get; set; }
public int calls { get; set; }
public string user_id { get; set; }
}
Example:
string json = #"{
""success"":true,
""code"":200,
""total"":2,
""data"":{
""1019588"":{
""name"":""(t) Bob Jones"",
""calls"":213,
""user_id"":""1019588""
},
""1019741"":{
""name"":""(t) Chris Smith"",
""calls"":387,
""user_id"":""1019741""
}
}
}";
var obj = System.Text.Json.JsonSerializer
.Deserialize<AgentPeformanceResponse>(json);

using System;
using System.Collections.Generic;
public class AgentPeformanceResponse
{
public bool success { get; set; }
public int code { get; set; }
public int total { get; set; }
public Dictionary<string, PerformanceReponse> data { get; set; }
}
public class PerformanceReponse
{
public string name { get; set; }
public int calls { get; set; }
public string user_id { get; set; }
}
public class Program
{
public static void Main()
{
var json = "{\"success\":true,\"code\":200,\"total\":2,\"data\":{\"1019588\":{\"name\":\"(t) Bob Jones\",\"calls\":213,\"user_id\":\"1019588\"},\"1019741\":{\"name\":\"(t) Chris Smith\",\"calls\":387,\"user_id\":\"1019741\"}}}";
var result = System.Text.Json.JsonSerializer.Deserialize<AgentPeformanceResponse>(json);
Console.WriteLine(result.code);
Console.WriteLine(result.data["1019741"].name);
}
}
The output will be
200
(t) Chris Smith
Fiddle for you
https://dotnetfiddle.net/lQu2Ln

all code you really need
Dictionary<string, PerformanceReponse> dict = JsonDocument.Parse(json).RootElement
.GetProperty("data").Deserialize<Dictionary<string,PerformanceReponse>>();
//or if you want a list
List<PerformanceReponse> list = data.Select(d=>d.Value).ToList();
or using Newtonsoft.Json
Dictionary<string,PerformanceReponse> dict = JObject.Parse(json)
["data"].ToObject<Dictionary<string,PerformanceReponse>>();
how to use
PerformanceReponse data1019588= dict["1019588"];

Related

JSON DeserializeObject shows 0

hello i've got some problems in c#(xamarin)
i followed XXX tutorials about pharsing..
I only need the Value.
Can someone tell me how i solve that problem?
my Json:
{
"Header":{
"Version":5,
"Device":"80",
"Timestamp":1610066048
},
"Data":{
"Inputs":[
{
"Number":2,
"AD":"A",
"Value":{
"Value":62.0,
"Unit":"1"
}
}
]
},
"Status":"OK",
"Status code":0
}
C#
var client = new WebClient();
string json = client.DownloadString("https://XXXXXXX.com/heizung.php");
Value1 news = JsonConvert.DeserializeObject<Value1>(json);
Ausgabe.Text = news.Value;
My Class
public class Header
{
public int Version { get; set; }
public string Device { get; set; }
public int Timestamp { get; set; }
}
public class Value1
{
public string Value { get; set; }
public string Unit { get; set; }
}
public class Input
{
public int Number { get; set; }
public string AD { get; set; }
public Value1 Value { get; set; }
}
public class Data
{
public List<Input> Inputs { get; set; }
}
public class Root
{
public Header Header { get; set; }
public Data Data { get; set; }
public string Status { get; set; }
public int Statuscode { get; set; }
}
Thanks, i hope y'all have a nice day.
Deserialize Root object and track value down:
Root news = JsonConvert.DeserializeObject<Root>(json);
Ausgabe.Text = news.Data.Inputs[0].Value.Value;
You should deserialize your json as a Root class:
var root = JsonConvert.DeserializeObject<Root>(json);
After the root object is deserialized you can select whatever value you need. E.g.:
var values = root.Data.Inputs.Select(i => i.Value.Value); // string sequence

C# - Store JSON array string into SQL table

I am new to C#
Following is the JSON string I am getting from the web API.
I am trying to store the JSON string into a class and then store the JSON string into an SQL table.
But the C# code is failing to deserialize JSON into class. And the message box returns the null exception error.
JSON
{
"Count":3,
"data":[
{
"Cost1":{
"amount":111,
"currencyCode":"ABC"
},
"Cost2":{
"amount":22.2,
"currencyCode":"XYZ"
},
"Id":"007"
},
{
"Cost1":{
"amount":555,
"currencyCode":"ABC"
},
"Cost2":{
"amount":444,
"currencyCode":"XYZ"
},
"Id":"008"
},
{
"Cost1":{
"amount":666,
"currencyCode":"ABC"
},
"Cost2":{
"amount":8882,
"currencyCode":"XYZ"
},
"Id":"009"
}
],
"pending":[
],
"#up":"Test Data"
}
C# Code
public class ParceJSN {
public int Count {
get;
set;
}
public string data {
get;
set;
}
public string pending {
get;
set;
}
public string up {
get;
set;
}
}
public void Main() {
Task < string > task = MakeRequest(db_token); //Returns the JSON string
var fr = task.Result;
ParceJSN rst = JsonConvert.DeserializeObject < ParceJSN > (fr.ToString());
MessageBox.Show(rst.TotalCount.ToString());
Dts.TaskResult = (int) ScriptResults.Success;
}
Your C# model is incorrect. Here's a really handy tool that I use when I need to generate C# classes based on some JSON - json2csharp.com
The correct class is:
public class Cost1 {
public int amount { get; set; }
public string currencyCode { get; set; }
}
public class Cost2 {
public double amount { get; set; }
public string currencyCode { get; set; }
}
public class Datum {
public Cost1 Cost1 { get; set; }
public Cost2 Cost2 { get; set; }
public string Id { get; set; }
}
public class Root {
public int Count { get; set; }
public List<Datum> data { get; set; }
public List<object> pending { get; set; }
[JsonProperty("#up")]
public string Up { get; set; }
}
Now that you have the correct model, you can now do the following to deserialize your JSON string into a Root object which is defined above:
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(YOUR_JSON_STRING);

Deserialise JSON containing numeric key. Json.NET [duplicate]

This question already has answers here:
Deserialise JSON containing numeric key with Json.NET
(3 answers)
Closed 2 years ago.
I want to deserialize the JSON (using Json.NET) to an object. But can't, because the class name would need to begin with a number.
{
"status":"ok",
"meta":{
"count":1
},
"data":{
"7887207":{
"global_rating":9524,
"statistics":{
"random":{
"damage_dealt":54395747,
"wins":17502,
"hits_percents":74,
"battle_avg_xp":797,
"battles":31389
}
},
"last_battle_time":1600087522
}
}
}
How could I deserialize this JSON containing a number? I tried to use following guide (Deserialise JSON containing numeric key with Json.NET)
public class MetaGetPlayerStats
{
public int count { get; set; }
}
public class RandomGetPlayerStats
{
public int damage_dealt { get; set; }
public int wins { get; set; }
public int hits_percents { get; set; }
public int battle_avg_xp { get; set; }
public int battles { get; set; }
}
public class StatisticsGetPlayerStats
{
public RandomGetPlayerStats random { get; set; }
}
public class AccountGetPlayerStats
{
public int global_rating { get; set; }
public StatisticsGetPlayerStats statistics { get; set; }
public int last_battle_time { get; set; }
}
public class AccountInfo
{
[JsonProperty("data")]
public Dictionary<int, AccountGetPlayerStats> AccountInfoStats { get; set; }
}
public class GetPlayerStats
{
public string status { get; set; }
public MetaGetPlayerStats meta { get; set; }
public AccountInfo data { get; set; }
}
But it doesn't work. It saw fields "status" and "meta", but "data" == null Image
AccountInfo is excess. data is a dictionary. This will work.
public class GetPlayerStats
{
public string status { get; set; }
public MetaGetPlayerStats meta { get; set; }
public Dictionary<string, AccountGetPlayerStats> data { get; set; }
}
You just need to change your GetPlayerStats class like this:
public class GetPlayerStats
{
public string status { get; set; }
public MetaGetPlayerStats meta { get; set; }
[JsonProperty("data")]
public Dictionary<string, JObject> AccountInfoStats { get; set; }
// public AccountInfo data { get; set; }
}
then you can proceed to the logic, follow reference.
Deserialize JSON with "random" key

Json not mapping properly in C#

Here is a json document that I wanted to map it to C# poco classes. I wrote some classes but they didn't work. I got null in my result object. Any ideas?
I used Newtonsoft's json converter.
{
"retrieval-response":{
"cdata":{
"identifier":"777400",
"document-count":"62"
},
"index":"10",
"count":"25"
}
}
C# map classes;
public class result
{
[JsonProperty("retrieval-response")]
public aResult res { get; set; }
public int index { get; set; }
public int count { get; set; }
}
public class aResult
{
public cdata data { get; set; }
}
public class cdata
{
[JsonProperty("identifier")]
public string identif { get; set; }
[JsonProperty("document-count")]
public string count { get; set; }
}
You model is wrong. Try this:
public class Wrapper
{
[JsonProperty("retrieval-response")]
public Result Result { get; set; }
}
public class Result
{
[JsonProperty("cdata")]
public Data Data { get; set; }
public int Index { get; set; }
public int Count { get; set; }
}
public class Data
{
[JsonProperty("identifier")]
public string Identifier { get; set; }
[JsonProperty("document-count")]
public string Count { get; set; }
}
Then you can deserialize it with the following line:
var myResult = JsonConvert.DeserializeObject<Wrapper>(json);
Please note that I've also wrote your property and class names in pascal case. These are the naming conventions from Microsoft.

How can I take the contents of a C# class and put into / take out of a string?

I have the following two classes:
public class TestQuestionModel
{
public TestQuestionModel()
{
this.Answers = new List<TestQuestionAnswerModel>();
}
public int TestId { get; set; }
public int TestQuestionId { get; set; }
public int QuestionNumber { get; set; }
public virtual ICollection<TestQuestionAnswerModel> Answers { get; set; }
}
public class TestQuestionAnswerModel
{
public int AnswerUId { get; set; }
public bool? Correct { get; set; }
public bool? Response { get; set; }
public string Text { get; set; }
}
What I would like to do is to store the Answers into a string and put into this class:
public class TestQuestion
{
public int TestId { get; set; }
public int TestQuestionId { get; set; }
public int QuestionNumber { get; set; }
public string AnswerString { get; set; }
}
Can someone tell me how I can do this in both directions (putting it in the string and taking it out)
Possible way:
public string Serialize(ICollection<TestQuestionAnswerModel> answers)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(answers);
}
public ICollection<TestQuestionAnswerModel> Deserialize(string data)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return (ICollection<TestQuestionAnswerModel>)serializer.Deserialize<ICollection<TestQuestionAnswerModel>>(data);
}

Categories