JSON Convert Deserialize Object - c#

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; }

Related

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);

JSON with Array Respone from API

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}");

Deserialize JSON to Nested Model

I have a model like below:
public class YourInformationInputModel
{
public YourInformationInputModel()
{
PrimaryBuyerInformation = new PrimaryBuyerInformationInputModel();
}
public PrimaryBuyerInformationInputModel PrimaryBuyerInformation { get; set; }
public bool TermsCondition { get; set; }
}
PrimaryBuyerInputModel like below:
public class PrimaryBuyerInformationInputModel
{
[Required]
public string BuyerFirstName { get; set; }
public string BuyerMiddleInitial { get; set; }
[Required]
public string BuyerLastName { get; set; }
}
and when I am submitting my form then I am getting JSON like below:
{
"PrimaryBuyerInformation.BuyerFirstName": "Sunil",
"PrimaryBuyerInformation.BuyerMiddleInitial": "",
"PrimaryBuyerInformation.BuyerLastName": "Choudhary",
"TermsCondition": "true"
}
When I am trying to deserialize this json the TermsCondition property successfully done, but the property of PrimaryBuyerInformation is not mapped.
var myObject = JsonConvert.DeserializeObject<YourInformationInputModel>(json);
Any idea how to do that ?
Kindly take a cue from the code below, i tested it and you should be able to get your value as request. This solves the issue of you trying to access the property you have mapped in a dot property name format.
Instead your object should be nested in a curly brace showing that the other property belongs to PrimaryBuyerInformationInputModel which is another object entirely.
Best Regards,
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var json = #"{'PrimaryBuyerInformation': {'buyerFirstName': 'Sunil','buyerMiddleInitial': '','buyerLastName': 'Choudhary'},'termsCondition': false}";
var obj = JsonConvert.DeserializeObject<YourInformationInputModel>(json);
Console.WriteLine(obj.PrimaryBuyerInformation.BuyerFirstName);
}
}
public class YourInformationInputModel
{
public YourInformationInputModel()
{
PrimaryBuyerInformation = new PrimaryBuyerInformationInputModel();
}
public PrimaryBuyerInformationInputModel PrimaryBuyerInformation { get; set; }
public bool TermsCondition { get; set; }
}
public class PrimaryBuyerInformationInputModel
{
public string BuyerFirstName { get; set; }
public string BuyerMiddleInitial { get; set; }
public string BuyerLastName { get; set; }
}

Binding JSON values in my server side is getting failed

I want to use the json values in my c# code. So I have written the code like below
public static void WriteToIEMService(string jsonValue)
{
string TimeFormatText = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss");
string strFileCreationDate = DateTime.Now.ToString("dd/MM/yyyy");
string strFileName = ConfigurationManager.AppSettings["IEM_SERVICEFILE"].ToString();
try
{
using (StreamWriter sw = File.CreateText(ConfigurationManager.AppSettings["LogFileDirectory"].ToString() + strFileName + "_" + strFileCreationDate + ".txt"))
{
List<MasterServiceResponse> records = JsonConvert.DeserializeObject<List<MasterServiceResponse>>(jsonValue);
sw.WriteLine("IEM Service started and send data to IEM below");
foreach (MasterServiceResponse record in records)
{
sw.WriteLine(record.SapId);
}
}
}
catch (Exception)
{
throw;
}
}
But I am getting error as
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[IPColoBilling_BKP.App_Code.MasterServiceResponse]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Please help
EDIT
My json values is as below
{"SiteData":[{"SAPId":"I-UW-SRPR-ENB-I001","SiteRFEIDate":"03-11-2014","SiteRFSDate":"03-11-2014","ID_OD":"ID","ID_ODchangeDate":"04-11-2018","NoofRRHBase":"0","RRHBaseChangeEffectiveDate":"","No_Of_Tenancy":"3","TenancyChangeEffectiveDate":"03-11-2014","SiteStatus":"Active","SiteDropDate":""}]}
UPDATE
public class MasterServiceResponse
{
public string SapId { get; set; }
public string AcknowledgementID { get; set; }
public string FlagResponse { get; set; }
public string ResponseMessage { get; set; }
public string GisStatus { get; set; }
public string GisSendDate { get; set; }
public string SiteRFEIDate { get; set; }
public string SiteRFSDate { get; set; }
public string SiteRRHDate { get; set; }
public string NoofRRHBase { get; set; }
}
Update: A stated by Panagiotis Kanavos, You are not creating Root object, so you have to restructure your models.
Don't know what your Model looks like, But this error message says your giving json object where it is expecting JSON array,
Below is the model you should be using
public class SiteData
{
public string SAPId { get; set; }
public string SiteRFEIDate { get; set; }
public string SiteRFSDate { get; set; }
public string ID_OD { get; set; }
public string ID_ODchangeDate { get; set; }
public string NoofRRHBase { get; set; }
public string RRHBaseChangeEffectiveDate { get; set; }
public string No_Of_Tenancy { get; set; }
public string TenancyChangeEffectiveDate { get; set; }
public string SiteStatus { get; set; }
public string SiteDropDate { get; set; }
}
public class RootObject
{
public List<SiteData> SiteData { get; set; }
}
You also have to change the deserializing code
E.g.
RootObject records = JsonConvert.DeserializeObject<RootObject>(jsonValue);
foreach (SiteData record in records.SiteData)
{
sw.WriteLine(record.SapId);
}
As the error mentions, you cannot deserialize JSON object to list. So instead of:
List<MasterServiceResponse> records = JsonConvert.DeserializeObject<List<MasterServiceResponse>>(jsonValue);
You should update have something like:
MyObject obj = JsonConvert.DeserializeObject<MyObject>(jsonValue);
The exception message tells you that the JSON string contains single object, but you're tried to deserialize it into List<MasterServiceResponse> collection.
You should create a class to hold List<MasterServiceResponse>:
public class SiteData
{
public List<MasterServiceResponse> MasterServiceResponse { get; set; }
}
Then you should replace this line:
List<MasterServiceResponse> records = JsonConvert.DeserializeObject<List<MasterServiceResponse>>(jsonValue);
to return single object like this:
SiteData records = JsonConvert.DeserializeObject<SiteData>(jsonValue);
Reference:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1
Because your JSON start with a key "SiteData" which has an array value, you need to create a helper class to match that structure (e.g. class SiteResponse) with a property named SiteData of type List<MasterServiceResponse>.
Code:
public class SiteResponse
{
public List<MasterServiceResponse> SiteData { get; set; }
}
private static void TestJson()
{
var jsonValue = "{\"SiteData\":[{\"SAPId\":\"I-UW-SRPR-ENB-I001\",\"SiteRFEIDate\":\"03-11-2014\",\"SiteRFSDate\":\"03-11-2014\",\"ID_OD\":\"ID\",\"ID_ODchangeDate\":\"04-11-2018\",\"NoofRRHBase\":\"0\",\"RRHBaseChangeEffectiveDate\":\"\",\"No_Of_Tenancy\":\"3\",\"TenancyChangeEffectiveDate\":\"03-11-2014\",\"SiteStatus\":\"Active\",\"SiteDropDate\":\"\"}]}";
var siteResponse = JsonConvert.DeserializeObject<SiteResponse>(jsonValue);
List<MasterServiceResponse> records = siteResponse.SiteData;
}
Working demo here:
https://dotnetfiddle.net/wzg8AK

Deserialize multiple XML tags to single C# object

I have class structure as follows
public class Common
{
public int price { get; set; }
public string color { get; set; }
}
public class SampleProduct:Common
{
public string sample1 { get; set; }
public string sample2 { get; set; }
public string sample3 { get; set; }
}
I have XML file as follows
<ConfigData>
<Common>
<price>1234</price>
<color>pink</color>
</Common>
<SampleProduct>
<sample1>new</sample1>
<sample2>new</sample2>
<sample3>new123</sample3>
</SampleProduct>
</ConfigData>
Now I wanted to deserialize full XML data to SampleProduct object (single object).I can deserialize XML data to different object but not in a single object. Please help.
If you create the XML yourself Just do it like this:
<ConfigData>
<SampleProduct>
<price>1234</price>
<color>pink</color>
<sample1>new</sample1>
<sample2>new</sample2>
<sample3>new123</sample3>
</SampleProduct>
</ConfigData>
Otherwise, if you get the XML from other sources, do what Kayani suggested in his comment:
public class ConfigData
{
public Common { get; set; }
public SampleProduct { get; set; }
}
But don't forget that the SampleProduct created in this manner don't have "price" and "color" properties and these should be set using created Common instance
Here is the complete solution using the provided XML from you.
public static void Main(string[] args)
{
DeserializeXml(#"C:\sample.xml");
}
public static void DeserializeXml(string xmlPath)
{
try
{
var xmlSerializer = new XmlSerializer(typeof(ConfigData));
using (var xmlFile = new FileStream(xmlPath, FileMode.Open))
{
var configDataOSinglebject = (ConfigData)xmlSerializer.Deserialize(xmlFile);
xmlFile.Close();
}
}
catch (Exception e)
{
throw new ArgumentException("Something went wrong while interpreting the xml file: " + e.Message);
}
}
[XmlRoot("ConfigData")]
public class ConfigData
{
[XmlElement("Common")]
public Common Common { get; set; }
[XmlElement("SampleProduct")]
public SampleProduct XSampleProduct { get; set; }
}
public class Common
{
[XmlElement("price")]
public string Price { get; set; }
[XmlElement("color")]
public string Color { get; set; }
}
public class SampleProduct
{
[XmlElement("sample1")]
public string Sample1 { get; set; }
[XmlElement("sample2")]
public string Sample2 { get; set; }
[XmlElement("sample3")]
public string Sample3 { get; set; }
}
This will give you a single Object with all the elements you need.

Categories

Resources