JSON with Array Respone from API - c#

i have a HTTPclient and im sending request to a Server.
The response from the server is a JSON. In this Json is also an array.
I want do display the information from the JSON in the consol.
I get all information from the JSON, but i dont get the array displayed in my console.
The JSON looks like this:
{
"Name1": "Karl",
"Name2": "Peter",
"Name3": "Wilhelm",
"PreNames": {
"PreName": "Werner",
"PreName2": "Josef"
}
}
So now my Code so far:
public class PreNames //for Array
{
public string PreName { get; set; }
public string PreName2{ get; set; }
}
public class Names//for JSON
{
public string Name1{ get; set; }
public string Name2{ get; set; }
public string Name3{ get; set; }
}
And my Main:
if (Response().IsSuccessStatusCode)
{
var namesJ= Response().Content.ReadAsAsync<IEnumerable<Names>>().Result;
var preNamesJ= await Response().Content.ReadAsAsync<List<PreNames>>();
foreach (var a in namesJ)
{
Console.WriteLine("Name1: {0}", a.Name1);
foreach(var b in preNamesJ)
{
Console.WriteLine("{0}", b.PreName);
}
}
So in the console are all names displayed, but not the PreNames so i cant get the PreNames from the array in the JSON...
I Hope somebody could help me :)

Add the PreNames property to your Names class and only read one time.
public class Names//for JSON
{
public string Name1{ get; set; }
public string Name2{ get; set; }
public string Name3{ get; set; }
public List<PreNames> PreNames { get; set;}
}
Once you read in the result one time, you can access the elements via the main object
var namesJ= Response().Content.ReadAsAsync<Names>().Result;
foreach(var names in namesJ.PreNames)
{
Console.WriteLine(names.PreName);
}
updated
Since you changed the json and made PreNames just an object instead of an array, simply access the property of related object.
public class Names//for JSON
{
public string Name1{ get; set; }
public string Name2{ get; set; }
public string Name3{ get; set; }
public PreNames PreNames { get; set;}
}
var namesJ= Response().Content.ReadAsAsync<Names>().Result;
Console.WriteLine(namesJ.PreNames.Name);

#Leonc443, Here is a working code
using Newtonsoft.Json; //add this nuget package
using System;
namespace ConsoleApp
{
class Program
{
public static void Main(string[] args)
{
string json = #"{
'Name1': 'Karl',
'Name2': 'Peter',
'Name3': 'Wilhelm',
'PreNames': {
'PreName': 'Werner',
'PreName2': 'Josef'
}
}"; // data received from api
var names = JsonConvert.DeserializeObject<Names>(json);
Console.WriteLine(names.Name1); // Karl
Console.WriteLine(names.Name2); //Peter
Console.WriteLine(names.Name3); //Wilhelm
Console.WriteLine(names.PreNames.PreName); //Werner
Console.WriteLine(names.PreNames.PreName2); // Josef
}
}
public class Names
{
public string Name1 { get; set; }
public string Name2 { get; set; }
public string Name3 { get; set; }
public PreNames PreNames { get; set; }
}
public class PreNames
{
public string PreName { get; set; }
public string PreName2 { get; set; }
}
}
Please let me know if this helps

In case your Json looks like:
{
"Name1": "Karl",
"Name2": "Peter",
"Name3": "Wilhelm",
"PreNames": {
"PreName": "Werner",
"PreName2": "Josef"
}
}
If the PreNames are in the Names, you shuld add a PreNames field to the Names Class.
public class Names
{
public string Name1 { get; set; }
public string Name2 { get; set; }
public string Name3 { get; set; }
public PreNames PreNames { get; set; }
}
Then you can read the inner PreNames:
foreach (var b in a.Prenames) {
Console.WriteLine(b.PreName);
}
But I'm not sure if I understand your question.

I don't have sufficient reputation to comment, so... I'll give it a try.
Edited after proper json updated in Answer.
Change your class Names
public class Names
{
public string Name1 { get; set; }
public string Name2 { get; set; }
public string Name3 { get; set; }
public PreNames PreNames { get; set; }
}
Then deserialize it with JsonConvert
var json = await Response().Content.ReadAsStringAsync();
var names = JsonConvert.DeserializeObject<Names>(json);
Then access data
Console.WriteLine($"Name 1: {names.Name1}");
Console.WriteLine($"Prename 1: {names.PreNames.PreName}");

Related

deserialize API response with different json value in the result

I'm querying an external service and wanted to deserialize the response into a customer object but the issue is response for each customer may be different. some customer may have Sales entity in the response and few may have Marketing.
The json property for sales entity is SalesId and for marketing is MarketingId. Can you advise whether the model I use to store result is correct or any improvement ? If so, how would I deserialize the response without knowing the correct json property ?
For Customer 66666
{
"customerId": "66666",
"customerName": "test1234",
"dependentEntity": [
{
"SalesId": "3433434",
"SalesPersonName": "343434",
"SaleSource": "StorePurchase"
}
]
}
For Customer 5555
{
"customerId": "55555",
"customerName": "test2",
"dependentEntity": [
{
"MarketingId": "3433434",
"MarketingAppName": "343434",
"MarketingSource": "Online"
}
]
}
Here is the Model I'm thinking but not sure the correct one
public class Customer
{
public string customerId { get; set; }
public string customerName { get; set; }
public IList<T> dependentList { get; set; }
}
public class Dependent
{
[JsonProperty("Id")]
public string Id { get; set; }
public string Name { get; set; }
public string Source { get; set; }
}
You could probably try something like the following one:
public class DependentEntity
{
[JsonProperty("SalesId")]
public string SalesId { get; set; }
[JsonProperty("SalesPersonName")]
public string SalesPersonName { get; set; }
[JsonProperty("SaleSource")]
public string SaleSource { get; set; }
[JsonProperty("MarketingId")]
public string MarketingId { get; set; }
[JsonProperty("MarketingAppName")]
public string MarketingAppName { get; set; }
[JsonProperty("MarketingSource")]
public string MarketingSource { get; set; }
}
public class Customer
{
[JsonProperty("customerId")]
public string CustomerId { get; set; }
[JsonProperty("customerName")]
public string CustomerName { get; set; }
[JsonProperty("dependentEntity")]
public IList<DependentEntity> DependentEntity { get; set; }
}
We have a type for DependentEntity that has both the attributes of Marketing and Sales object. After parsing your input, you could create a logic (checking the attributes) based on which you could check if a DependentEntity is a Marketing or a Sales object.
The above classes was generated using, jsonutils.
If we can assume that the dependentEntity contains only a single type of objects then you can use json.net's schema to perform branching based on the matching schema.
So, lets suppose you have these dependent entity definitions:
public class DependentMarket
{
public string MarketingId { get; set; }
public string MarketingAppName { get; set; }
public string MarketingSource { get; set; }
}
public class DependentSales
{
public string SalesId { get; set; }
public string SalesPersonName { get; set; }
[JsonProperty("SaleSource")]
public string SalesSource { get; set; }
}
...
Then you can use these classes to generate json schemas dynamically:
private static JSchema marketSchema;
private static JSchema salesSchema;
//...
var generator = new JSchemaGenerator();
marketSchema = generator.Generate(typeof(DependentMarket));
salesSchema = generator.Generate(typeof(DependentSales));
And finally you can do the branching like this:
var json = "...";
var semiParsedJson = JObject.Parse(json);
JArray dependentEntities = (JArray)semiParsedJson["dependentEntity"];
JObject probeEntity = (JObject)dependentEntities.First();
if (probeEntity.IsValid(marketSchema))
{
var marketEntities = dependentEntities.ToObject<List<DependentMarket>>();
...
}
else if (probeEntity.IsValid(salesSchema))
{
var salesEntities = dependentEntities.ToObject<List<DependentSales>>();
...
}
else if ...
else
{
throw new NotSupportedException("The provided json format is not supported");
}

How to generate a JSON class with dynamic name

I don't know if there is an existing name for that case, but I'm trying to retrieve data from NASA API (https://api.nasa.gov/) and I have a simple challenge to catch a list of objects near earth. Here is the JSON response I have from the GET request I do to "https://api.nasa.gov/neo/rest/v1/feed?...."
{
"links": {
"next": "http://www.neowsapp.com/rest/v1/feed?start_date=2021-07-04&end_date=2021-07-04&detailed=false&api_key=NjgpxgSbYHXyFSBI3HaOhRowtjMZgAKv2t4DMRym",
"prev": "http://www.neowsapp.com/rest/v1/feed?start_date=2021-07-02&end_date=2021-07-02&detailed=false&api_key=NjgpxgSbYHXyFSBI3HaOhRowtjMZgAKv2t4DMRym",
"self": "http://www.neowsapp.com/rest/v1/feed?start_date=2021-07-03&end_date=2021-07-03&detailed=false&api_key=NjgpxgSbYHXyFSBI3HaOhRowtjMZgAKv2t4DMRym"
},
"element_count": 6,
"near_earth_objects": {
"2021-07-03": [
{
"links": {
"self": "http://www.neowsapp.com/rest/v1/neo/3701710?api_key=NjgpxgSbYHXyFSBI3HaOhRowtjMZgAKv2t4DMRym"
},
"id": "3701710",
"neo_reference_id": "3701710",
"name": "(2014 WF497)",
"nasa_jpl_url": "http://ssd.jpl.nasa.gov/sbdb.cgi?sstr=3701710",
"absolute_magnitude_h": 20.23,
"estimated_diameter": {
"kilometers": {
}
And that's the way it is built in Visual Studio (using the Special Paste option for JSON)
public class NearEarthObject
{
public Links links { get; set; }
public int element_count { get; set; }
public Near_Earth_Objects near_earth_objects { get; set; }
}
public class Links
{
public string next { get; set; }
public string prev { get; set; }
public string self { get; set; }
}
public class Near_Earth_Objects
{
public _20210703[] _20210703 { get; set; }
}
public class _20210703
{
public Links1 links { get; set; }
public string id { get; set; }
public string neo_reference_id { get; set; }
public string name { get; set; }
public string nasa_jpl_url { get; set; }
public float absolute_magnitude_h { get; set; }
public Estimated_Diameter estimated_diameter { get; set; }
public bool is_potentially_hazardous_asteroid { get; set; }
public Close_Approach_Data[] close_approach_data { get; set; }
public bool is_sentry_object { get; set; }
}
The question is, inside of the element "near_earth_objects", there is an element called "2021-07-03" (the date of the data I requested), the problem is that I am trying to include it into a DataGridView made in .NET C# (Windows Forms, but that doesn't matters here, I think) and the user wants to get the information by date. So, "2021-07-03" is a valid member just for one day, and the user should be able to get data from multiple days.
So, is there a way in C# to get all child objects inside of near_earth_objects without knowing their names since there will be the option to search for asteroids from date X to Y in my application?
Using System.Text.Json
The API response will map to the following classes
public class Neo
{
public Links Links { get; set; }
public int ElementCount { get; set; }
public Dictionary<string, List<NearEarthObject>> NearEarthObjects { get; set; }
}
public class Links
{
public string Next { get; set; }
public string Prev { get; set; }
public string Self { get; set; }
}
public class NearEarthObject
{
public Links Links { get; set; }
public string Id { get; set; }
public string Name { get; set; }
// Other properties
}
The NearEarthObjects is simply a Dictionary, where the key is the formatted date and value is a List containing NearEarthObject
The PropertyNamingPolicy will allow us to support the API's underscore property naming convention.
public class UnderscoreNamingPolicy : JsonNamingPolicy
{
public override string ConvertName(string name)
{
return name.Underscore();
}
}
Example usage
// using using System.Text.Json;
var response = await new HttpClient().GetStringAsync(url);
var neo = JsonSerializer.Deserialize<Neo>(response, new JsonSerializerOptions
{
PropertyNamingPolicy = new UnderscoreNamingPolicy()
});
foreach(var neos in neo.NearEarthObjects)
{
Console.WriteLine(neos.Key);
}
use System.Text.Json, JsonNamingPolicy
demo code
public class DynamicNamePolicy : JsonNamingPolicy
{
public override string ConvertName(string name)
{
var today = DateTime.Today.ToString("yyyy-MM-dd");
if (name.Equals("DateData")) //model property name
return today; //convert to json string property name
return name;
}
}
//data deserialize
string data = ""; //json string
var obj = JsonSerializer.Deserialize<NearEarthObject>(data, new JsonSerializerOptions
{
PropertyNamingPolicy = new DynamicNamePolicy(),
});

How do I parse this JSON data in C# and would it be more benefical to simply switch over to javascript?

I'm looking to parse this JSON and I've had nothing but problems. The link to the JSON is here. I'm trying to access the "href" field. While writing this up, I realized that that the data field is actually an array so that is part of my problem.
class Program
{
static void Main(string[] args)
{
var json = System.IO.File.ReadAllText(#"C:\Users\...\file.json");
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(json);
var x = myDeserializedClass.result.extractorData.data;
Console.Write(x.ToString());
}
public class Newcolumn
{
public string text { get; set; }
public string xpath { get; set; }
public string href { get; set; }
public string filepath { get; set; }
public string fileMimeType { get; set; }
public int fileTotalBytes { get; set; }
public string fileLastModifiedTime { get; set; }
}
public class Group
{
public List<Newcolumn> Newcolumn { get; set; }
}
public class Datum
{
public List<Group> group { get; set; }
}
public class ExtractorData
{
public string url { get; set; }
public List<Datum> data { get; set; }
}
public class PageData
{
public int statusCode { get; set; }
public long timestamp { get; set; }
}
public class Inputs
{
public string _url { get; set; }
}
public class Result
{
public ExtractorData extractorData { get; set; }
public PageData pageData { get; set; }
public Inputs inputs { get; set; }
public string taskId { get; set; }
public long timestamp { get; set; }
public int sequenceNumber { get; set; }
}
public class Root
{
public string url { get; set; }
public Result result { get; set; }
}
}
This ends up returning: System.Collections.Generic.List`1[ConsoleApp3.Datum]
I notice that the field name data actually turns into an array though I'm not sure how to structure that. data.[0].new Column.[0].group.etc... does not work obviously. The space in the "new Column" field is also problematic. Additionally, when I debug and look at the JSON viewer, the "new column field is null. I also tried this code:
public static void Main()
{
var json = System.IO.File.ReadAllText(#"C:\Users\...\file.json");
dynamic stuff = JsonConvert.DeserializeObject(json);
var a = stuff.result.extractorData.data;
string b = a.ToString();
Console.WriteLine(b);
Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
This actually does return the data field object however, if I do stuff.result.extractorData.data.group; I get this:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
HResult=0x80131500
Message='Newtonsoft.Json.Linq.JArray' does not contain a definition for 'group'
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>
I assume that this is probably because of the array contained within the data field, regardless the "new Column' field is also an issue with this method due to the space.
in your above code
public class ExtractorData
{
public string url { get; set; }
public List<Datum> data { get; set; }
}
where data is List and you are trying to access as string
Console.Write(x.ToString());
in data variable Datum is List ( where your variable have multiple Data) and in every element there is a List. (Nestest List Concept Applied in This JSON)
Try to Add Break Point on below Line and check the line by line Excution of Code.
var a = stuff.result.extractorData.data;
After Looking Your JSON File Image Try This Code
Console.Write(a.FirstOrDefault()?.group.FirstOrDefault()?.Newcolumn.FirstOrDefault()?.href);

Not able validate data condition based on the json element attribute value from a json using c#

I have a json file, where i have to validate a json attribute element value based on another json element attribute value. But if there json elements with the same name. It always takes the last value always instead of parsing the json data fully. Please guide me.
Below the sample json file
{
"PLMXML":{
"language":"en-us",
"author":"Developer",
"date":"2020-05-22",
"traverseRootRefs":"#id6",
"Operation":{
"id":"id21",
"subType":"BS4_BaOP",
"catalogueId":"70700000209604"
},
"Operation":{
"id":"id28",
"subType":"BS4_BaOP",
"catalogueId":"70700000209603"
},
"OperationRevision":{
"id":"id6",
"subType":"BS4_BaOPRevision",
"masterRef":"#id21",
"revision":"A1"
}
}
}
And below the code which im trying to use
public void Readjsonfile(string jsondata)
{
var message = JsonConvert.DeserializeObject<plmxmldatamodel>(jsondata);
if (String.Equals(message.PLMXML.traverseRootRefs.Substring(1), message.PLMXML.OperationRevision.id))
{
Console.WriteLine("Condtion1");
if (String.Equals(message.PLMXML.OperationRevision.masterRef.Substring(1), message.PLMXML.Operation.id))
{
Console.WriteLine("Condition_2");
//Do something based on the condtion
}
}
}
public class Operation
{
public string id { get; set; }
public string subType { get; set; }
public string catalogueId { get; set; }
}
public class OperationRevision
{
public string id { get; set; }
public string subType { get; set; }
public string masterRef { get; set; }
}
public class PLMXML
{
public string language { get; set; }
public string author { get; set; }
public string date { get; set; }
public string traverseRootRefs { get; set; }
public Operation Operation { get; set; }
public OperationRevision OperationRevision { get; set; }
}
public class plmxmldatamodel
{
public PLMXML PLMXML { get; set; }
}
When i try to dedug this in the second if condtion, the value for message.PLMXML.Operation.id is always id28 , because of which second if condition fails. While the first if condition is passed as there is only one message.PLMXML.OperationRevision.id. i wanted behaviour where it would check complete json data and check if message.PLMXML.Operation.id with value id21 is present or not , So my data gets passed. Please kindly guide me here.I am very new to C# here.
From my observation you have couple of issues.
What happen you have double keys, and your parser taking the last value not the first one.
First of all your json should be corrected. I assume you have access to change your json and operation should be an array like follow:
{
"PLMXML":{
"language":"en-us",
"author":"Developer",
"date":"2020-05-22",
"traverseRootRefs":"#id6",
"Operations":[
{
"id":"id21",
"subType":"BS4_BaOP",
"catalogueId":"70700000209604"
},
{
"id":"id28",
"subType":"BS4_BaOP",
"catalogueId":"70700000209603"
}
],
"OperationRevision":{
"id":"id6",
"subType":"BS4_BaOPRevision",
"masterRef":"#id21",
"revision":"A1"
}
}
}
When array in place than use an online tool like to validate your json and use this tool to create a model.
Your model will be like this:
public partial class PlmxmlDataModel
{
[JsonProperty("PLMXML")]
public Plmxml Plmxml { get; set; }
}
public partial class Plmxml
{
[JsonProperty("language")]
public string Language { get; set; }
[JsonProperty("author")]
public string Author { get; set; }
[JsonProperty("date")]
public DateTimeOffset Date { get; set; }
[JsonProperty("traverseRootRefs")]
public string TraverseRootRefs { get; set; }
[JsonProperty("Operations")]
public Operation[] Operations { get; set; }
[JsonProperty("OperationRevision")]
public OperationRevision OperationRevision { get; set; }
}
public partial class OperationRevision
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("subType")]
public string SubType { get; set; }
[JsonProperty("masterRef")]
public string MasterRef { get; set; }
[JsonProperty("revision")]
public string Revision { get; set; }
}
public partial class Operation
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("subType")]
public string SubType { get; set; }
[JsonProperty("catalogueId")]
public string CatalogueId { get; set; }
}
And your method like this:
public void Readjsonfile(string jsondata)
{
var message = JsonConvert.DeserializeObject<PlmxmlDataModel>(jsondata);
if (String.Equals(message.Plmxml.TraverseRootRefs.Substring(1), message.Plmxml.OperationRevision.Id))
{
Console.WriteLine("Condtion1");
if (String.Equals(message.Plmxml.OperationRevision.MasterRef.Substring(1), message.Plmxml.Operations[0].Id))
{
Console.WriteLine("Condition_2");
//Do something based on the condtion
}
}
}
Now in your method I am looking for array index 0 with contain id 28, but if you are look for id 28 in any of the array then you can do some thing like:
if (message.Plmxml.Operations.Any(e => e.Id == message.Plmxml.OperationRevision.MasterRef.Substring(1)))

JSON Convert Deserialize Object

I have an issue with my JSON to XML code. It's not assigning the values to the Object and I cannot figure out why. Please let me know what I am doing wrong.
My C# code:
using Newtonsoft.Json;
using System.Xml;
namespace JSONTest
{
public class Program
{
static void Main(string[] args)
{
string fileName = "C:\\Code\\JSONTest\\data\\response.xml";
// Convert XML Data into JSON Data
XmlDocument xmlFile = new XmlDocument();
xmlFile.Load(fileName);
string jsonData = JsonConvert.SerializeXmlNode(xmlFile);
// Convert JSON Data into Object
RootObject root = JsonConvert.DeserializeObject<RootObject>(jsonData);
var data = root.RESPONSE_GROUP;
Console.ReadLine();
}
}
public class RootObject
{
public RESPONSEGROUP RESPONSE_GROUP { get; set; }
}
public class RESPONSEGROUP
{
public string MISMOVersionID { get; set; }
public object RESPONDING_PARTY { get; set; }
public object RESPOND_TO_PARTY { get; set; }
public RESPONSE RESPONSE { get; set; }
}
public class RESPONSE
{
public string ResponseDateTime { get; set; }
public KEY KEY { get; set; }
public STATUS STATUS { get; set; }
}
public class KEY
{
public string _Name { get; set; }
public string _Value { get; set; }
}
public class STATUS
{
public string _Code { get; set; }
public string _Condition { get; set; }
public string _Description { get; set; }
public string _Name { get; set; }
}
}
XML
<RESPONSE_GROUP MISMOVersionID="2.4">
<RESPONDING_PARTY/>
<RESPOND_TO_PARTY/>
<RESPONSE ResponseDateTime="2015-02-19T10:32:11-06:00">
<KEY _Name="LOSClientID" _Value="3000799866"/>
<STATUS _Code="S0010" _Condition="Success" _Description="TEST DESC" _Name="Complete"/>
</RESPONSE>
</RESPONSE_GROUP>
My "JSONData" string:
{"RESPONSE_GROUP":{"#MISMOVersionID":"2.4","RESPONDING_PARTY":null,"RESPOND_TO_PARTY":null,"RESPONSE":{"#ResponseDateTime":"2015-02-19T10:32:11-06:00","KEY":{"#_Name":"LOSClientID","#_Value":"3000799866"},"STATUS":{"#_Code":"S0010","#_Condition":"Success","#_Description":"THIS IS THE DESCRIPTION.","#_Name":"Complete"}}}}
The value of: root.RESPONSE_GROUP.MISMOVersionID is NULL as well as any other values that should have been populated. I know I'm doing something wrong here, but I cannot figure out what it is.
Please help! Thanks in advance.
The problem is that your JSON contains # signs in front of some property names. For example:
"#MISMOVersionID":"2.4"
There are two options here:
Fix the JSON to not have that, e.g. "#MISMOVersionID":"2.4"
Use JsonPropertyAttribute to tell Json.NET which property name to expect in the JSON, e.g.
[JsonProperty("#MISMOVersionID")]
public string MISMOVersionID { get; set; }

Categories

Resources