ASP.NET C# Deserialized Json Object - c#

I have json like this
{
"reader_name":"FX9600EAF871",
"mac_address":"84:24:8D:FC:0E:AD",
"tag_reads":[
{
"epc":"E28068100000003C0A05E3B7",
"antennaPort":"1",
"peakRssi":"-31",
"seenCount":"2458",
"timeStamp":"14/02/2022 22:50:24:356",
"channelIndex":"5"
}
]
}
I try using this code
public class TagRead
{
public string epc { get; set; }
public string pc { get; set; }
public string antennaPort { get; set; }
public string peakRssi { get; set; }
public string seenCount { get; set; }
public string timeStamp { get; set; }
public string phase { get; set; }
public string channelIndex { get; set; }
public string isHeartBeat { get; set; }
}
public class Hdr
{
public string reader_name { get; set; }
public string mac_address { get; set; }
public List<TagRead> tag_reads { get; set; }
}
var deserialized = Newtonsoft.Json.JsonConvert.DeserializeObject<Hdr>(json);
When try to print reader name using
deserialized.reader_name
it gets result FX9600EAF87
but when print
deserialized.tag_reads
it get nothing?
my question is How to get epc & antennaport data?
thank you

Because deserialized.tag_reads is a collection instead of base type or string, you might get the result that you didn't want to get.
How to get epc & antennaport data?
you might try to use deserialized.tag_reads with foreach to iterator the collection then do your logic
var deserialized = Newtonsoft.Json.JsonConvert.DeserializeObject<Hdr>(json);
foreach(var item in deserialized.tag_reads){
//item.epc
//item.antennaPort
}
c# online

Related

Json DeserializedObject how do I call the returned values

How do I call the values from the Wrapper items. I assumed it would be for example items.SysName but no luck. I am calling a query that returns a list of text in json format that is then filtered with the jsonConvert I am just unable to call the results but I can view that they are there in the debugger. The end result is I will create a list of the SysName values and return said list.
public async Task<string> Table()
{
try
{
using (HttpClient client = GetClient())
{
var response = client.GetAsync("unimportant");
response.Wait();
if (response.Result.IsSuccessStatusCode)
{
var result = await response.Result.Content.ReadAsStringAsync();
Wrapper items = JsonConvert.DeserializeObject<Wrapper>(result);
return null;
}
};
} catch (Exception ex)
{
_logger.LogWarning(ex, $"Failed to retrieve requested Table |{ex.Message}");
Console.WriteLine(ex.Message);
}
return null;
}
Wrapper class
public class Question
{
[JsonProperty("link")]
public string Link { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
public class SysPackage
{
[JsonProperty("link")]
public string Link { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
public class SysScope
{
[JsonProperty("link")]
public string Link { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
public class Result
{
[JsonProperty("rec_misc")]
public string RecMisc { get; set; }
[JsonProperty("question")]
public Question Question { get; set; }
[JsonProperty("sys_mod_count")]
public string SysModCount { get; set; }
[JsonProperty("sys_updated_on")]
public string SysUpdatedOn { get; set; }
[JsonProperty("sys_tags")]
public string SysTags { get; set; }
[JsonProperty("sys_class_name")]
public string SysClassName { get; set; }
[JsonProperty("published_ref")]
public string PublishedRef { get; set; }
[JsonProperty("sys_id")]
public string SysId { get; set; }
[JsonProperty("sys_package")]
public SysPackage SysPackage { get; set; }
[JsonProperty("inactive")]
public string Inactive { get; set; }
[JsonProperty("sys_update_name")]
public string SysUpdateName { get; set; }
[JsonProperty("sys_updated_by")]
public string SysUpdatedBy { get; set; }
[JsonProperty("sys_created_on")]
public string SysCreatedOn { get; set; }
[JsonProperty("sys_name")]
public string SysName { get; set; }
[JsonProperty("sys_scope")]
public SysScope SysScope { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("sys_created_by")]
public string SysCreatedBy { get; set; }
[JsonProperty("misc")]
public string Misc { get; set; }
[JsonProperty("order")]
public string Order { get; set; }
[JsonProperty("sys_policy")]
public string SysPolicy { get; set; }
}
public class Wrapper
{
[JsonProperty("result")]
public IList<Result> Result { get; set; }
}
}
Image showing that results do show up.
items is a Wrapper which contains a collection of Result : items.Result.
You can iterate through it to access the results one by one. One way to do it is by using a foreach loop
foreach (Result result in items.Result)
{
string sysName = result.SysName;
}
You can also use LinQ to retrieve all of the sysNames
IEnumerable<string> sysNames = items.Result.Select(result => result.SysName);
If you only care about the first result, just use
Result result = items.Result.First();
string sysName = result.SysName;
PS :
Renaming Wrapper.Result to Wrapper.Results and var items = ... to var wrapper = ... is more explicit about your data.

JSON Deserializer returning NULL Values

I am trying to consume a REST API via a C# Console Application and I've got as far as getting the webservice to return the JSON file, with the format:
{"status":200,"result":{"postcode":"SW1W0DT","quality":1,"eastings":528813,"northings":178953,"country":"England","nhs_ha":"London","longitude":-0.145828,"latitude":51.494853,"european_electoral_region":"London","primary_care_trust":"Westminster","region":"London","lsoa":"Westminster 023E","msoa":"Westminster 023","incode":"0DT","outcode":"SW1W","parliamentary_constituency":"Cities of London and Westminster","admin_district":"Westminster","parish":"Westminster, unparished area","admin_county":null,"admin_ward":"Warwick","ccg":"NHS Central London (Westminster)","nuts":"Westminster","codes":{"admin_district":"E09000033","admin_county":"E99999999","admin_ward":"E05000647","parish":"E43000236","parliamentary_constituency":"E14000639","ccg":"E38000031","nuts":"UKI32"}}}
I have created a class AddressInfo which is as follows:
public class AddressInfo {
public string postcode { get; set; }
public int quality { get; set; }
public int eastings { get; set; }
public int northings { get; set; }
public string country { get; set; }
public string nhs_ha { get; set; }
public string admin_county { get; set; }
public string admin_district { get; set; }
public string admin_ward { get; set; }
public double longitude { get; set; }
public double latitude { get; set; }
public string parliamentary_constituency { get; set; }
public string european_electoral_region { get; set; }
public string primary_care_trust { get; set; }
public string region { get; set; }
public string parish { get; set; }
public string lsoa { get; set; }
public string msoa { get; set; }
public string ccg { get; set; }
public string nuts { get; set; }
public object codes { get; set; }
}
The code to call the API and get the values is:
string strJSON = string.Empty;
strJSON = rClient.makeRequest();
Console.Write(strJSON);
AddressInfo AI = new AddressInfo();
AI = Newtonsoft.Json.JsonConvert.DeserializeObject<AddressInfo>(strJSON);
However, when I debug, AI is returning the values as "NULL".
Thanks
Notice that your JSON has a nested structure. The AddressInfo is contained within its result property, it isn't at the top level.
Your actual class structure to deserialize the entire JSON response should look something like this (I've called the class JsonResponse but you can name it whatever you want):
class JsonResponse{
public int status { get; set; }
public AddressInfo result { get; set; }
}
Then deserialize it like this:
JsonResponse res = JsonConvert.DeserializeObject<JsonResponse>(strJSON);
AddressInfo addressInfo = res.result;
You're missing the fact that you need an outer class that has the properties int status and AdressInfo result.
You don't need to create a separate class to deserialize the entire response, this can be done dynamically to achieve desired result:
var source = "(your JSON");
dynamic data = JObject.Parse(source);
var d = JsonConvert.SerializeObject(data.result);
AddressInfo account = JsonConvert.DeserializeObject<AddressInfo>(d);
Your JSON is nested. The result is a nested object. That's why you are experiencing this issue.

Deserializing Json string with C# using Newtonsoft.JSON

I have read some articles but didnt fix my problem , i have a problem with JSON string when deserialize, here the string
{"table":"sy_version","effected":2,"data":[{"mod_id":"CS","sub_mod":"sbm_sl.exe","version":"2015.11.07.1","upload_date ":"2015-11-10 11:34:13"},{"mod_id":"FA","sub_mod":"sbm_fa.exe","version":"2015.11.09","upload_date ":"2015-11-10 11:34:13"}]}
And this is my class
public class Datum
{
public string mod_id { get; set; }
public string sub_mod { get; set; }
public string version { get; set; }
public DateTime upload_date { get; set; }
}
public class sy_periode
{
public string table { get; set; }
public int effected { get; set; }
public IList<Datum> datas { get; set; }
}
public static void test(string str) {
// dynamic sy_periode = JsonConvert.DeserializeObject(str);
var sy_periode = JsonConvert.DeserializeObject<sy_periode>(str);
foreach (var data in sy_periode.datas)
{
Console.WriteLine(data.sub_mod);
}
}
When I executed, string table and effected have value, but datas is null, this is the error message
Object reference not set to an instance of an object.
It shouldn't be datas, it should have the same name as JSON object: data.
Here is the correct classes structure:
public class Datum
{
public string mod_id { get; set; }
public string sub_mod { get; set; }
public string version { get; set; }
public DateTime upload_date { get; set; }
}
public class sy_periode
{
public string table { get; set; }
public int effected { get; set; }
public IList<Datum> data { get; set; }
}
Also, note that in JSON your upload_date properties have an odd whitespace in the end: upload_date. It may be a typo. However, if it is an actual input and since C# member name cannot contain spaces, you can try to specify the name in order to serialize it:
[JsonProperty(PropertyName = "upload_date ")]
public DateTime upload_date { get; set; }
I am not quite sure that it will work, but I see no reasons of why it shouldn't.

How do I convert a complex json object to CLR object with json.net?

sorry for a dumb question but I haven't found any solution for this.
Here is my JSON:
{
"Id": "1",
"Parent.Id": "1",
"Agent.Id": "1",
"Agent.Profile.FullName": "gena",
"Fee": "10.1200",
"FeeManagementDate": "29/11/2013",
"Contact.Name": "Genady",
"Contact.Telephone": "000000000",
"Contact.Email": "gena#email.com",
"AgreementUrl": "http://www.test.com/agreement"
}
Here is my object
public class ManagementDetailsViewModel : ViewModel<int> {
public ManagementDetailsViewModel() {
}
public string AgreementUrl { get; set; }
public HttpPostedFileBase AgreementFile { get; set; }
public decimal Fee { get; set; } // payment data
public DateTime? FeeDate { get; set; }
public string FeeManagementDate {
get { return FeeDate != null ? FeeDate.Value.ToString("dd/MM/yyyy") : DateTime.Now.ToString("dd/MM/yyyy"); }
set {
FeeDate = Convert.ToDateTime(value);
}
}
public BusinessViewModel Parent { get; set; }
public MemberViewModel Agent { get; set; }
public Contact Contact { get; set; }
}
How do I convert the json string to object (with inner objects)?
Json.Net needs some help because your json object contain propery names, which is not valid in c# like(Agent.Id)
var obj = JsonConvert.DeserializeObject<MyObj>(json);
How do I convert the json string to object (with inner objects)?
Since your json is flat(not containing sub objects) you have to post process your deserialized object if you want to use it that way/
public class MyObj
{
public string Id { get; set; }
[JsonProperty("Parent.Id")]
public string ParentId { get; set; }
[JsonProperty("Agent.Id")]
public string AgentId { get; set; }
[JsonProperty("Agent.Profile.FullName")]
public string ProfileFullName { get; set; }
public string Fee { get; set; }
public string FeeManagementDate { get; set; }
[JsonProperty("Contact.Name")]
public string ContactName { get; set; }
[JsonProperty("Contact.Telephone")]
public string ContactTelephone { get; set; }
[JsonProperty("Contact.Email")]
public string ContactEmail { get; set; }
public string AgreementUrl { get; set; }
}

Navigating JSON data in c#

I'm trying to check if a twitch.tv stream is online or not via c#. Currently I have:
private bool checkStream(String chan)
{
using (var w = new WebClient()) {
String json_data = w.DownloadString("https://api.twitch.tv/kraken/streams/" + chan);
JObject stream = JObject.Parse(json_data);
print(json_data); //just for testing purposes
if (stream["stream"] != null)
{
print("YIPPEE");
}
}
return false;
}
Here's the twitch JSON API for what I'm downloading: https://github.com/justintv/Twitch-API/blob/master/v2_resources/streams.md#get-streamschannel
As you can see, if a stream is currently offline, the stream field just says null. But obviously, it's still there, so my if(stream["stream"]!=null) check doesn't work. Never used JSON or Newtonsoft's json.net before, so I'm kind of at a loss for what to do. Thanks in advance for any help!
You need to create a class that you can de-serialize the json to. For instance, if you receive json that looks like this
MyJson = {
Prop1 : "Property1",
Prop2 : "Property2"
}
then you'll need to create a class that acts as a contract between your program and the JSON stream.
public class MyJsonClass{
public string Prop1;
public string Prop2;
public MyJsonClass(){
}
}
Now, you can deserialize the json to your C# class and check it for any null values:
// Create a MyJson class instance by deserializing your json string
string myJsonString = ...//get your json string
MyJsonClass deserialized = JsonConvert.DeserializeObject<MyJsonClass>(myJsonString);
if ( deserialized.Prop1 == null )
//etc etc etc
Here's a full processor for that Json response (Disclaimer: I used http://json2csharp.com/ for this code ) :
public class Links
{
public string channel { get; set; }
public string self { get; set; }
}
public class Links2
{
public string self { get; set; }
}
public class Links3
{
public string stream_key { get; set; }
public string editors { get; set; }
public string subscriptions { get; set; }
public string commercial { get; set; }
public string videos { get; set; }
public string follows { get; set; }
public string self { get; set; }
public string chat { get; set; }
public string features { get; set; }
}
public class Channel
{
public string display_name { get; set; }
public Links3 _links { get; set; }
public List<object> teams { get; set; }
public string status { get; set; }
public string created_at { get; set; }
public string logo { get; set; }
public string updated_at { get; set; }
public object mature { get; set; }
public object video_banner { get; set; }
public int _id { get; set; }
public string background { get; set; }
public string banner { get; set; }
public string name { get; set; }
public string url { get; set; }
public string game { get; set; }
}
public class Stream
{
public Links2 _links { get; set; }
public string broadcaster { get; set; }
public string preview { get; set; }
public long _id { get; set; }
public int viewers { get; set; }
public Channel channel { get; set; }
public string name { get; set; }
public string game { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public Stream stream { get; set; }
}
and here's how to use it :
bool StreamOnline = false;
using (var w = new WebClient())
{
var jsonData = w.DownloadData("https://api.twitch.tv/kraken/streams/" + + chan);
var s = new DataContractJsonSerializer(typeof(RootObject));
using (var ms = new MemoryStream(jsonData))
{
var obj = (RootObject)s.ReadObject(ms);
StreamOnline = obj.stream == null;
}
}
return StreamOnline;
Please note that you need to reference System.Runtime.Serialization and add using System.Runtime.Serialization.Json; to use DataContractJsonSerializer. If you don't need every detail just make the stream property of type object (in the RootObject class) and check whether it's null or not.
Have you tried this. The HasValues is a bool property that checks if there are child tokens, if its value is null there will not be any child tokens.
if (stream["stream"].HasValues)
{
print("YIPPEE");
}else
{
print("No Stream");
}

Categories