Deserializing just a single node of a JSON response - c#

I have a json response like
{
"appStatus":{
"status":true
},
"lastSyncDate":"06-07-2013 13.54.27",
"configResponse":{
"status":{
"status":true
},
"configs":{
"APPLOGENABLED":{
"configCode":"APPLOGENABLED",
"configDesc":"enable or disable logging from front end",
"configType":"TAB",
"configValue":"Y"
},
"COMMENTSTIMER":{
"configCode":"COMMENTSTIMER",
"configDesc":"timer for comments in seconds",
"configType":"TAB",
"configValue":"60"
},
"SUMMARYTIMER":{
"configCode":"SUMMARYTIMER",
"configDesc":"timer for summary in seconds",
"configType":"TAB",
"configValue":"30"
},
"ALERTSTIMER":{
"configCode":"ALERTSTIMER",
"configDesc":"timer for alerts in seconds",
"configType":"TAB",
"configValue":"60"
}
},
"lastSyncDate":"06/07/2013 13.48.13"
}
}
Using json.NET, I want to extract configResponse into dictionary. I know i can directly convert a Dictionary object like this
JsonConvert.DeserializeObject<Dictionary<string,string>>()....
but since configResponse is a sub element, I am not able to parse it as required.
I want to deserialize the above json response as
public class ConfigResponse
{
public Status status { get; set; }
public Dictionary<string, ConfigurationItem> configs { get; set; }
public string lastSyncDate { get; set; }
}
public class ConfigurationItem
{
public String configCode { get; set; }
public String configDesc { get; set; }
public String configType { get; set; }
public String configValue { get; set; }
}

You can parse JSON string into JObject, get sub-object "configResponse", then deserialize it into ConfigResponse. It's one line of code:
JObject.Parse("{...}")["configResponse"].ToObject<ConfigResponse>()
If you need a custom serializer to set deserialization options, you can pass it to ToObject<T>() method.

i have only use this method and it worked.
await JsonConvert.DeserializeObjectAsync<ConfigResponse>(jsontoobject, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

Related

c# json get only array from json results

I am new to c# json.
I would only want to get CardTransactions array , "status": 0, and ignore the rest of the json values.
May I know how to achieve with c#.
{
"response":{
"timeStamp":7812371,
"totalCount":1,
"CardTransactions":[
{
"transactionDate":"2021-08-16",
"invoiceNo":"KM011782313",
"amount":2000.00
}
],
"status":0,
"message":"dakjalsda"
},
"status":null,
"message":null
}
Create a model class that looks that way
public class Response
{
[JsonProperty("CardTransactions")]
public List<CardTransaction> CardTransactions { get; set; }
[JsonProperty("status")]
public int Status { get; set; }
}
public class Root
{
[JsonProperty("response")]
public Response Response { get; set; }
}
and use Newtonsoft to convert JSON to object like the following
Root response = JsonConvert.DeserializeObject<Root>(yourJson);

Deserialize issue in C# Json

PageParameters have dynamic values. I tried to add it like below.
{
"Message": [
{
"TextMessage": "Hello World",
"Notification": [{
"Page": "Order",
"OpenPage": true,
"PageParameters":[ {"filedName": "400","filedvalue": "test","test": "444"}]
} ]
}
]
}
C# Code
var notification = notificationRequest?.NotificationMessage[0].ToString();
var NotificationObj = JsonConvert.DeserializeObject<NotificationObj>(notification);
public class NotificationObj
{
public string TextMessage { get; set; }
public string AppName { get; set; }
public List<Notifications> Notification { get; set; }
}
public class Notifications
{
public string PageName { get; set; }
public bool OpenPage { get; set; }
public List<PageParameter> PageParameters { get; set; }
}
public class PageParameter
{
List<string> PageParameters = new List<string>();
}
My PageParameter have dynamic values. Its getting multiple values. So i tried to add it as a List. But its not adding values when Deserialize Json. Other values are adding. Please help to solve this.
Check my answer here. You essentially need to apply that on your PageParameter class
PageParameters is an array of Key-value pairs, which would require the use of a Dictionary in C#.
Update PageParameter to the following and re-run your deserialization:
public class PageParameter
{
Dictionary<string, string> PageParameters = new Dictionary<string, string>();
}

C# Json how to deserialize something with a key that could be any kind of int

I'm working on a Xamarin App, and I use Newtonsoft for Json.
But I'm having trouble with processing some data that I get back.
{
"ok": true,
"payment-methods": [
{
"id": "39sahf92ka9s02",
"type": "ideal",
"options": {
"issuers": {
99: "Test Issuer"
}
}
}
],
}
I don't know how to get to the Test Issuer, because the Key value could be any integer.
A Dictionary makes a lot of sense to use, but then I get the following exception: "System.NullReferenceException: Object reference not set to an instance of an object. json"
I have the following as Model:
[JsonObject(MemberSerialization.OptIn)]
public class PaymentOptions
{
[JsonProperty("ok")]
public Boolean OK { get; set; }
[JsonProperty("payment-methods")]
public List<PaymentMethods> PaymentMethods { get; set; }
}
public class PaymentMethods
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("options")]
public Options Options { get; set; }
}
public class Options
{
[JsonProperty("issuers")]
public IDictionary<int, string> Issuers { get; set; }
}
I deserialize the Json through the following:
var deserializedGetPaymentOptions = JsonConvert.DeserializeObject<Models.PaymentMethods>(await responseGetPaymentOptions.Content.ReadAsStringAsync());
And after that I try to read it by using it in a foreach loop:
foreach (KeyValuePair<int, string> issuerFromDict in deserializedGetPaymentOptions.Options.Issuers)
Have you tried with 99 as string in the json representation ?
...
"issuers": {
"99": "Test Issuer"
}
...
You should let newtonsoft deals with the conversion to int.
I fixed it by doing the following:
var deserializedGetPaymentOptions = JsonConvert.DeserializeObject<Models.PaymentOptions>(await responseGetPaymentOptions.Content.ReadAsStringAsync());
foreach (var desPayOp in deserializedGetPaymentOptions.PaymentMethods) {
Debug.WriteLine("start foreach");
foreach (KeyValuePair<int, string> issuerFromDict in desPayOp.Options.Issuers)
{
Debug.WriteLine(issuerFromDict.Key.ToString() + " : " + issuerFromDict.Value);
}
}
I now deserialize it from PaymentOptions instead of PaymentMethods, then loop through the List and after that through the dictionary.

how to get "start" item value using C# linq query?

[{"service":"xxx",
"processes":
[
{
"name":"tomcat",
"command":{
"start": "/server/tomcat01/bin/tomcat01.sh start",
"stop": "/server/tomcat01/bin/tomcat01.sh stop",
"restart": "/server/tomcat01/bin/tomcat01.sh restart",
}
}
]
}]
how to get start item value with using c# linq?
Given the following concrete classes:
public class Command
{
public string start { get; set; }
public string stop { get; set; }
public string restart { get; set; }
}
public class Process
{
public string name { get; set; }
public Command command { get; set; }
}
public class Services
{
public string service { get; set; }
public List<Process> processes { get; set; }
}
You can deserialize the json and retrieve a list of all starts with the following:
var json = #"[{""service"":""xxx"", ""processes"": [{""name"":""tomcat"", ""command"":{""start"":""/server/tomcat01/bin/tomcat01.shstart"", ""stop"":""/server/tomcat01/bin/tomcat01.shstop"", ""restart"":""/server/tomcat01/bin/tomcat01.shrestart"", } } ] }]";
var deserialized = JsonConvert.DeserializeObject<List<Services>>(json);
var starts = deserialized.Select(x => x.processes.Select(p => p.command?.start));
Using the Json.Net LINQ-to-JSON API you could do this:
string command = JToken.Parse(json)
.SelectMany(jo => jo.SelectToken("processes"))
.Select(jo => (string)jo.SelectToken("command.start"))
.FirstOrDefault();
...which would return /server/tomcat01/bin/tomcat01.sh start given your JSON input.
Fiddle: https://dotnetfiddle.net/Ft3q2C
It seems that you want to deserialize your json string into C# class.
JavaScriptSerializer jss= new JavaScriptSerializer();
CustomClass tempClass = jss.Deserialize<CustomClass>(jsonString);
jsonString is json data which you mentioned in your question. You can then use linq over your class.

Deserialization and serialization using newtonsoft c#

My application is binding a REST API, that returns this to me:
{
key: "XXXX-XXXX",
fields: {
customfield_10913: {
value: "L2"
}
}
}
I'm using Newtonsoft JSON to serialize and deserialize and I've created these models to make it work:
public class Issue
{
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("fields")]
public Fields Fields { get; set; }
}
public class Fields
{
[JsonProperty("customfield_10913")]
public CustomField Level { get; set; }
}
public class CustomField
{
[JsonProperty("value")]
public string Value{ get; set; }
}
The application is deserializing everything ok, using this code:
T model = JsonConvert.DeserializeObject<T>(result);
After a lot of business logic, my WEB API should return a new JSON:
protected T Get()
{
return model;
}
And I've got everything like the JSON I've read from another API.
So, What I need?
I need to read the field CUSTOM_FIELDXXX, but I can't return it with this name in my WEB API. How could I read this field, but when I'm doing the serialization, it assume another one?
You may try below function
Issue model = deserializeObject<Issue>(result);
public T deserializeObject<T>(string result)
{
try
{
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
};
var items = (T)JsonConvert.DeserializeObject(result, typeof(T), settings);
return items;
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
}
If you can have any property name for your CustomField property, you can serialize that as a Dictionary<string, CustomField>, like so:
public class Issue
{
public Issue()
{
this.Fields = new Dictionary<string, CustomField>();
}
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("fields")]
public Dictionary<string, CustomField> Fields { get; set; }
}
Then you can use any string-valued name for your custom field.
Working fiddle.

Categories