How to deserialize strange JSON format in C# [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have this JSON response from a server:
"{\"Data\":[{\"AI\":\"(00)103002310000531111\",\"BatchId\":157,\"LogisticLevel\":7,\"ParentId\":-1,\"State\":1,\"SyncState\":-1,\"InternalID\":86996,\"ModifyReason\":null,\"AggregationDate\":\"1900-01-01T00:00:00\",\"CommissioningDate\":\"1900-01-01T00:00:00\",\"DecommissioningDate\":\"1900-01-01T00:00:00\",\"NumberOfChildren\":0,\"RejectCode\":-1,\"ShippingDate\":\"1900-01-01T00:00:00\",\"TotalNumberOfUnits\":1,\"CompanyPrefix\":\"030023\",\"FilterValue\":7,\"PackLevel\":1,\"ReferenceCode\":\"\",\"Schema\":1,\"SerialNumber\":\"1000053111\",\"IsGood\":true,\"Children\":[]}],\"Code\":10,\"Message\":\"Data retrieved\"}"
My responsbody it's wrong...much slashes...why ?
I serialize data with Newtonsoft JSON.
But the format isn't correct, I receive an error while deserializing on the client.
I saw that there're slashes in the JSON string. How can I solve this?
I use C#.

Your Json is valid and can be deserialized using JsonConvert:
public class Datum
{
public string AI { get; set; }
public int BatchId { get; set; }
public int LogisticLevel { get; set; }
public int ParentId { get; set; }
public int State { get; set; }
public int SyncState { get; set; }
public int InternalID { get; set; }
public object ModifyReason { get; set; }
public DateTime AggregationDate { get; set; }
public DateTime CommissioningDate { get; set; }
public DateTime DecommissioningDate { get; set; }
public int NumberOfChildren { get; set; }
public int RejectCode { get; set; }
public DateTime ShippingDate { get; set; }
public int TotalNumberOfUnits { get; set; }
public string CompanyPrefix { get; set; }
public int FilterValue { get; set; }
public int PackLevel { get; set; }
public string ReferenceCode { get; set; }
public int Schema { get; set; }
public string SerialNumber { get; set; }
public bool IsGood { get; set; }
public List<object> Children { get; set; }
}
public class RootObject
{
public List<Datum> Data { get; set; }
public int Code { get; set; }
public string Message { get; set; }
}
JsonConvert.DeserializeObject<RootObject>(
"{\"Data\":[{\"AI\":\"(00)103002310000531111\",\"BatchId\":157,\"LogisticLevel\":7,\"ParentId\":-1,\"State\":1,\"SyncState\":-1,\"InternalID\":86996,\"ModifyReason\":null,\"AggregationDate\":\"1900-01-01T00:00:00\",\"CommissioningDate\":\"1900-01-01T00:00:00\",\"DecommissioningDate\":\"1900-01-01T00:00:00\",\"NumberOfChildren\":0,\"RejectCode\":-1,\"ShippingDate\":\"1900-01-01T00:00:00\",\"TotalNumberOfUnits\":1,\"CompanyPrefix\":\"030023\",\"FilterValue\":7,\"PackLevel\":1,\"ReferenceCode\":\"\",\"Schema\":1,\"SerialNumber\":\"1000053111\",\"IsGood\":true,\"Children\":[]}],\"Code\":10,\"Message\":\"Data retrieved\"}"
).Dump();

String json= "{\"Data\":[{\"AI\":\"(00)103002310000531111\",\"BatchId\":157,\"LogisticLevel\":7,\"ParentId\":-1,\"State\":1,\"SyncState\":-1,\"InternalID\":86996,\"ModifyReason\":null,\"AggregationDate\":\"1900-01-01T00:00:00\",\"CommissioningDate\":\"1900-01-01T00:00:00\",\"DecommissioningDate\":\"1900-01-01T00:00:00\",\"NumberOfChildren\":0,\"RejectCode\":-1,\"ShippingDate\":\"1900-01-01T00:00:00\",\"TotalNumberOfUnits\":1,\"CompanyPrefix\":\"030023\",\"FilterValue\":7,\"PackLevel\":1,\"ReferenceCode\":\"\",\"Schema\":1,\"SerialNumber\":\"1000053111\",\"IsGood\":true,\"Children\":[]}],\"Code\":10,\"Message\":\"Data retrieved\"}";
dynamic bsObj = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(bsObj.ToString());
Console.WriteLine(bsObj.Data[0].BatchId.ToString()); //157
Console.WriteLine(bsObj.Code.ToString()); // 10
Console.WriteLine(bsObj.Message.ToString()); // Data retrieved

Related

Returning null value in JSON Deserialization [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 months ago.
Improve this question
I am trying to deserialize the json string in C#. Following is jsonstring I used. But after deserialize it is giving null value. So what's going wrong with me?
string res = #"{ ""root"":{""EmployeeMaster"":{""EmployeeMasterData"":[{""BasicDetails"":{ ""BasicDetail"":{ ""Action"":""Update"",""EmployeeCode"":""0076"",""L2ManagerCode"":2911}}},{""BasicDetails"":{""BasicDetail"":{ ""Designation"":""Branch Incharge"",""Action"":""Update"",""EmployeeCode"":1786,""SubDepartment"":""Branch Manager"",""Department"":""Operations"",""JOBROLE"":""Branch Manager"",}}},{""DependentDetails"":{""DependentDetail"":{""DateOfBirth"":""1972-07-31"",""DependentName"":""Ramani"",""Action"":""Create"",""EmployeeCode"":2923,""Address"":"""",""RelationshipType"":""Mother"",""Gender"":"""",""IsDependent"":""No""}}},{""ContactDetails"":{""ContactDetail"":[{""AddressLine2"":""Turvekere"",""AddressLine1"":""Hallada Hosahalli"",""Action"":""Update"",""Country"":""India"",""City"":""Tumkur"",""Pincode"":572227},{""AddressLine2"":"""",""AddressLine1"":"""",""Action"":""Update"",""State"":"""",""Country"":"""",""City"":"""",""Pincode"":""""}]}},{""BasicDetails"":{""BasicDetail"":{""Action"":""Create"",""L2ManagerName"":""Ratheesh P R"",""IsDisabled"":""No"",""L1ManagerCode"":2771,""SubDepartment"":""Collection Assistant"",""Gender"":""Male"",""EmploymentType"":""Permanent"",""Department"":""Operations"",""L1ManagerName"":""Arun K K"",""Designation"":""Collection Assistant"",""EmployeeCode"":201021,""L2ManagerCode"":2564,""FirstName"":""Vishnu"",""Title"":""Mr."",""EmploymentStatus"":""Active"",""MiddleName"":"""",""DisabilityType"":"""",""OfficialMailID"":"""",""Nationality"":""IND"",""DateOfRelieving"":"""",""DateOfJoining"":""2022-01-20"",""JOBROLE"":"""",""LastName"":""G"",""BirthDate"":""1995-08-28""}}}]}}}";
It's not working, because the primitive object is invalid. can anyone please help me to create the class file. thanks in advance
try this, it was tested in visual studio
var jsonParsed = JObject.Parse(json);
List<EmployeeMasterData> employeeMasterData = jsonParsed["root"]["EmployeeMaster"]
["EmployeeMasterData"].Select(x => AddItems(x)).ToList();
public static EmployeeMasterData AddItems(JToken jt)
{
var emd = new EmployeeMasterData();
foreach (var element in ((JObject)jt).Properties())
{
if (element.Name == "BasicDetails")
emd.BasicDetails = element.Value.ToObject<BasicDetails>();
if (element.Name == "DependentDetails")
emd.DependentDetails = element.Value.ToObject<DependentDetails>();
if (element.Name == "ContactDetails")
emd.ContactDetails = element.Value.ToObject<ContactDetails>();
}
return emd;
}
classes
public class EmployeeMasterData
{
public BasicDetails BasicDetails { get; set; }
public DependentDetails DependentDetails { get; set; }
public ContactDetails ContactDetails { get; set; }
}
public class EmployeeMaster
{
public List<EmployeeMasterData> EmployeeMasterData { get; set; }
}
public class Root
{
public EmployeeMaster EmployeeMaster { get; set; }
}
public class BasicDetail
{
public string Action { get; set; }
public string EmployeeCode { get; set; }
public int? L2ManagerCode { get; set; }
public string Designation { get; set; }
public string SubDepartment { get; set; }
public string Department { get; set; }
public string JOBROLE { get; set; }
public string L2ManagerName { get; set; }
public string IsDisabled { get; set; }
public string L1ManagerCode { get; set; }
public string Gender { get; set; }
public string EmploymentType { get; set; }
public string L1ManagerName { get; set; }
public string FirstName { get; set; }
public string Title { get; set; }
public string EmploymentStatus { get; set; }
public string MiddleName { get; set; }
public string DisabilityType { get; set; }
public string OfficialMailID { get; set; }
public string Nationality { get; set; }
public string DateOfRelieving { get; set; }
public string DateOfJoining { get; set; }
public string LastName { get; set; }
public string BirthDate { get; set; }
}
public class BasicDetails
{
public BasicDetail BasicDetail { get; set; }
}
public class DependentDetail
{
public string DateOfBirth { get; set; }
public string DependentName { get; set; }
public string Action { get; set; }
public string EmployeeCode { get; set; }
public string Address { get; set; }
public string RelationshipType { get; set; }
public string Gender { get; set; }
public string IsDependent { get; set; }
}
public class DependentDetails
{
public DependentDetail DependentDetail { get; set; }
}
public class ContactDetail
{
public string AddressLine2 { get; set; }
public string AddressLine1 { get; set; }
public string Action { get; set; }
public string Country { get; set; }
public string City { get; set; }
public object Pincode { get; set; }
public string State { get; set; }
}
public class ContactDetails
{
public List<ContactDetail> ContactDetail { get; set; }
}
Generally, I would suggest the NewtonSoft JSON library if you are working with JSON. You can serialize and deserialize JSON to class, and class to JSON.
With this library you must not parse JSON by yourself.
JSON Library
First of all, there are some errors in the Json format. There is an incorrect use of the icon. Additionally, if you specify string for Json, the \ add symbol is required for each ".
You do not need to write # in front of the string this time.
like this
\"DateOfJoining\":\"2022-01-20\"

Newtonsoft Json Convert does not convert json string to object

I have these classes
public class ResponseEntryInfoAndTollDue
{
public int Code { get; set; }
public string Message { get; set; }
public TagEntryInfo TagEntryInfo { get; set; }
public TollMatrix TollMatrix { get; set; }
public List<TagInfoParam> TagInfoParams { get; set; }
public ResponseEntryInfoAndTollDue()
{
TagEntryInfo = new TagEntryInfo();
TollMatrix = new TollMatrix();
TagInfoParams = new List<TagInfoParam>();
}
}
public class TagEntryInfo
{
public long TrxnID { get; set; }
public string TagRFIDNumber { get; set; }
public string EntryTrxnDTime { get; set; }
public int EntryPlaza { get; set; }
public short EntryLane { get; set; }
public string EntryDirection { get; set; }
public string EntryLaneType { get; set; }
public string PostingDateTime { get; set; }
public string Action { get; set; }
}
public class TollMatrix
{
public decimal TollDue { get; set; }
public decimal TollVat { get; set; }
public decimal TollNoVat { get; set; }
public bool IsDefaulted { get; set; }
}
public class TagInfoParam
{
public DateTime? AsOfDate { get; set; }
public Decimal? AvailableBalance { get; set; }
public string TagNumber { get; set; }
public string PLateNumber { get; set; }
public Int16 HonorPlate { get; set; }
public Int16 TagStatusID { get; set; }
public string TID { get; set; }
public string EPC { get; set; }
public string AccountTypeID { get; set; }
public Int16 AccountStatusID { get; set; }
public Int16 TagClassID { get; set; }
public Int16 Status { get; set; }
}
From a webservice I get this json string:
{"Result":{"Code":0,"Message":"With entry info computed toll due","TagEntryInfo":{"TrxnID":6666750,"TagRFIDNumber":"1234567890","EntryTrxnDTime":"2021-01-16 16:40:16.560","EntryPlaza":123,"EntryLane":1,"EntryDirection":"B","EntryLaneType":"A","PostingDateTime":"2021-01-16T16:43:16.05","Action":"A"},"TollMatrix":{"TollDue":164.0000,"TollVat":17.5700,"TollNoVat":146.4300,"IsDefaulted":false},"TagInfoParams":[{"AsOfDate":"2021-01-16T17:12:04.213","AvailableBalance":537.0000,"TagNumber":"1234567890","PLateNumber":"Q123","HonorPlate":1,"TagStatusID":1,"TID":"Elfkajs98","EPC":"889080990709","AccountTypeID":"REV","AccountStatusID":1,"TagClassID":1,"Status":1}]},"Id":351,"Exception":null,"Status":5,"IsCanceled":false,"IsCompleted":true,"CreationOptions":0,"AsyncState":null,"IsFaulted":false}
This is how I convert it:
var response = JsonConvert.DeserializeObject(ret);
I know that it doesn't get converted because this is what I get:
This is the result:
Why is this not being converted into an object?
As Fabio also mentioned that your json contains the attribute Result which is not part of your object so you can use below logic to deserialize
var jObj = JObject.Parse(json);
var responseEntryInfoAndTollDue = JsonConvert.DeserializeObject<ResponseEntryInfoAndTollDue>(jObj["Result"].ToString());
The above code first parse the Json to JObject and uses Result property to deserialize to ResponseEntryInfoAndTollDue object.
Check this fiddle - https://dotnetfiddle.net/7Pc3sJ

I am getting error while converting json to object

i am trying to convert JSON to object following is my json
{"entity":"event","account_id":"acc_8yTsyb2WJOlcka","event":"payment.captured","contains":["payment"],"payload":{"payment":{"entity":{"id":"pay_AKR45WLH0g1ANu","entity":"payment","amount":100,"currency":"INR","status":"captured","order_id":"order_AKR41LsWIgOAB1","invoice_id":null,"international":false,"method":"netbanking","amount_refunded":0,"refund_status":null,"captured":true,"description":"Admission Fees","card_id":null,"bank":"SBIN","wallet":null,"vpa":null,"email":"xxxxx.xxxx#xxx.xxx","contact":"xxxxx","notes":{"address":"NA","merchant_order_id":"2516"},"fee":2,"tax":0,"error_code":null,"error_description":null,"created_at":1528367383}}},"created_at":1528367384}
and the code I am trying to convert to object is
jsonString = JsonConvert.SerializeObject(documentContents);
RazorPayPayload desJsonString = JsonConvert.DeserializeObject<RazorPayPayload>(jsonString);
and the classes where I want to deserialized
public class RazorPayPayload
{
public string entity { get; set; }
public string account_id { get; set; }
public string events { get; set; }
public List<string> contains { get; set; }
public payments payload { get; set; }
public string created_at { get; set; }
}
public class payments
{
public Entities payment { get; set; }
}
public class notes
{
public string address { get; set; }
public string merchant_order_id { get; set; }
public string source { get; set; }
}
public class Entities
{
public Entity entity { get; set; }
}
public class Entity
{
public string id { get; set; }
public string entity { get; set; }
public string amount { get; set; }
public string currency { get; set; }
public string order_id { get; set; }
public string invoice_id { get; set; }
public string international { get; set; }
public string method { get; set; }
public string amount_refunded { get; set; }
public string refund_status { get; set; }
public string captured { get; set; }
public string description { get; set; }
public string card_id { get; set; }
public string bank { get; set; }
public string wallet { get; set; }
public string vpa { get; set; }
public string email { get; set; }
public string contact { get; set; }
public notes notes { get; set; }
public string fee { get; set; }
public string tax { get; set; }
public string error_code { get; set; }
public string error_description { get; set; }
}
I am getting the error "Error converting value to type 'FeePayr_Razor_Webhook.RazorPayPayload'"
Have you tried changing:
{"entity":"event","account_id":"acc_8yTsyb2WJOlcka","event":
to
{"entity":"event","account_id":"acc_8yTsyb2WJOlcka","events":
That would better match your class definition. Or rename your class field to event.
There is a useful visual studio function for converting a json object to c# classes.
Copy the JSON into the clipboard. (helps if the JSON object properties holds data, to determine the data type)
Go to visual studio and place cursor where you'd like to paste in the c# classes.
click edit => paste special => paste json as classes

Using a specific JSON url in C# code

I need to extract data from a JSON string from a specific url (this).
When I convert it into C# by using jsontocsharp.com it looks like this:
public class Publisher
{
public int id { get; set; }
public string name { get; set; }
}
public class Title
{
public int id { get; set; }
public string name { get; set; }
public int subscribers { get; set; }
}
public class Issue
{
public List<object> alternates { get; set; }
public string complete_title { get; set; }
public string cover_image { get; set; }
public string description { get; set; }
public string diamond_id { get; set; }
public int id { get; set; }
public bool is_parent { get; set; }
public double? issue_number { get; set; }
public string other { get; set; }
public double price { get; set; }
public Publisher publisher { get; set; }
public string release_date { get; set; }
public Title title { get; set; }
}
public class RootObject
{
public int count { get; set; }
public string date { get; set; }
public List<Issue> issues { get; set; }
public int next { get; set; }
public object prev { get; set; }
public int total { get; set; }
}
Now I need to use these as my classes so I can gather and use data on further layers of my project. But I don't know how should I put the url in my code. I think this is a very basic question but I couldn't quite get the answer I'm looking for in the other questions. Any help greatly appreciated thank you.

Cannot deserialize the current JSON object - Null List

I am using Newtonsoft.JSON in C# and I have JSON like this:
http://woothemes.github.io/woocommerce/rest-api/#get-orders
Note:
coupon_lines []
When I serialize the JSON, I get this error:
List<Order> result = JObject.Parse(GetJson(url))["orders"].ToObject<List<Order>>();
Here is the coupon json:
"coupon_lines":{"id":65,"code":"alank10","amount":"33.08"}
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WooCommerce.Core.Models.CouponLine]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
How do I serialize coupon_lines to List
public class CouponLine
{
public int id { get; set; }
public string code { get; set; }
public decimal amount { get; set; }
}
Here is my class:
public class CouponLines
{
public List<CouponLine> lines { get; set; }
}
public class Order
{
public int id { get; set; }
public string order_number { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
public DateTime completed_at { get; set; }
public string status { get; set; }
public string currency { get; set; }
public decimal total { get; set; }
public decimal subtotal { get; set; }
public int total_line_items_quantity { get; set; }
public decimal total_tax { get; set; }
public decimal total_shipping { get; set; }
public decimal cart_tax { get; set; }
public decimal shipping_tax { get; set; }
public decimal total_discount { get; set; }
public decimal cart_discount { get; set; }
public decimal order_discount { get; set; }
public string shipping_methods { get; set; }
public PaymentDetails payment_details { get; set; }
public BillingAddress billing_address { get; set; }
public ShippingAddress shipping_address { get; set; }
public string note { get; set; }
public string customer_ip { get; set; }
public string customer_user_agent { get; set; }
public string customer_id { get; set; }
public string view_order_url { get; set; }
public List<LineItem> line_items { get; set; }
public List<ShippingLine> shipping_lines { get; set; }
//public List<object> tax_lines { get; set; }
//public List<object> fee_lines { get; set; }
public CouponLines coupon_lines { get; set; }
public Customer customer { get; set; }
}
You should use some kind of "root" object that contains this list, for example:
var parsedResponse = JsonConvert.DeserializeObject<CouponLines>(jsonResponse);
//...
public class CouponLines
{
public List<CouponLine> order { get; set; }
}
The string from your example
"coupon_lines":{"id":65,"code":"alank10","amount":"33.08"}
is invalid JSON: to make it valid add { at the beginning and } at the end:
{"coupon_lines":{"id":65,"code":"alank10","amount":"33.08"}}
Also, you said, you want to deserialize list, and you do not have list in your example. To get list your JSON object should contain list of objects (even if there is one object) in square breckets []:
{
"coupon_lines":[
{
"id":65,
"code":"alank10",
"amount":"33.08"
}
//if you have several objects - put it here after comma:
//,
//{
// "id":100500,
// "code":"somecode",
// "amount":"33.08"
//}
]
}
I had a similar problem (and also similar reuqest with orders, lines, shippings etc...)
first thing is that:
in your json, you can receive your list as
"line_items" : null
without any problems
or also this one:
"line_items" : []
does the trick.
but if you want the perfect solution, so you can avoid to send the line_items parameter completely, the solution is pretty easy,
just decorate your property on the request with
[JsonProperty(Required = Required.AllowNull)]
public List<LineItem> line_items { get; set; }
it worked perfectly for me.

Categories

Resources