Converting json to class object - c#

And I have my object definition as:
public class sendSmsResult
{
public sendSmsResult()
{
MessageIdList=new List<MessageId>();
}
public string ErrorCode { get; set; }
public string PacketId { get; set; }
public List<MessageId> MessageIdList { get; set; }
}
public class MessageId
{
public MessageId()
{
messageid=new List<string>();
}
public List<string> messageid { get; set; }
}
After executing this:
IRestResponse response = client.Execute(request);
I am getting the jsonresult from "response.Content" as
"{\"sendSmsResult\":{\"ErrorCode\":\"0\",\"PacketId\":\"261633886\",\"MessageIdList\":{\"MessageId\":[\"7096779206\",\"-19\"]}}}"
after getting json string I am running this:
JsonConvert.DeserializeObject<sendSmsResult>(response.Content);
gives an error says:
{"Message":"An error has occurred.","ExceptionMessage":"Error
converting value
"{"sendSmsResult":{"ErrorCode":"0","PacketId":"261638899","MessageIdList":{"MessageId":["7097068828","-19"]}}}"
to type 'UME.WebApi.Models.sendSmsResult'. Path '', line 1, position

you need wrapper for sendSmsResult, like bellow:
class sendSmsResultWrapper {
public sendSmsResult sendSmsResult {get;set;}
}
And, typeof sendSmsResult.MessageIdList is MessageId, not List<MessageId>!!

For what it's worth json2csharp.com (no affiliation) suggests the following class structure for your sample data:
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class MessageIdList {
public List<string> MessageId { get; set; }
}
public class SendSmsResult {
public string ErrorCode { get; set; }
public string PacketId { get; set; }
public MessageIdList MessageIdList { get; set; }
}
public class Root {
public SendSmsResult sendSmsResult { get; set; }
}

Related

How to deserialize an object and pass it to a response model

i have a json string that i deserialize as follows.
using (var streamReader = new StreamReader(httpResponsePayment.GetResponseStream()))
{
var data = streamReader.ReadToEnd();
result = JsonConvert.DeserializeObject<TestResponse>(data);
}
the data object looks as follows
"{\"responseCode\":2402,\"responseMessage\":\"hello\",\"amount\":0,\"acquirer\":{\"account\":{\"Number\":\"4587-54884-784848\"},\"Tag\":\"TF1234569775548494\"}}"
i pass this object to my TestResponse class
public class TestResponse
{
public string responseCode { get; set; }
public string responseMessage { get; set; }
public int amount { get; set; }
}
i can pass the above 3 objects correctly. I dont know how to pass the acquirer object to the TestResponse
acquirer = new
{
account= new
{
Number="4587-54884-784848"
},
Tag= "TF1234569775548494"
}
i tried doing something like this
public class TestResponse
{
public string responseCode { get; set; }
public string responseMessage { get; set; }
public int amount { get; set; }
List<Acquirers> acquirer =new List<Acquirers>();
}
public class Acquirers
{
public string Tag { get; set; }
}
also tried
public class TestResponse
{
public string responseCode { get; set; }
public string responseMessage { get; set; }
public int amount { get; set; }
public string Number {get;set;} //returns null
public string Tag {get;set;} // returns null
}
can someone please guide me
class Program
{
static void Main(string[] args)
{
var json = "{\"responseCode\":2402,\"responseMessage\":\"hello\",\"amount\":0,\"acquirer\":{\"account\":{\"Number\":\"4587-54884-784848\"},\"Tag\":\"TF1234569775548494\"}}";
var result = JsonConvert.DeserializeObject<Root>(json);
}
}
public class Account
{
public string Number { get; set; }
}
public class Acquirer
{
public Account account { get; set; }
public string Tag { get; set; }
}
public class Root
{
public int responseCode { get; set; }
public string responseMessage { get; set; }
public int amount { get; set; }
public Acquirer acquirer { get; set; }
}
you can using this link = https://json2csharp.com/
for convert model

How to deserialize json body with "0" in parameter

I'm using a API that give me this json as a response,
This is json response body :
{
"meta":{
"status":200,
"message":"success"
},
"data":{
"0":{
"MsgID":"2661689817",
"Status":"6",
"SendTime":"2021-10-3114:30:04",
"DeliverTime":"2021-10-31 14:30:07"
}
}
}
My problem is "0":{... in this body.
How can I deserialize this into a Class.
it can't deserialize on "string _0" prop.
As the #TheGeneral says, this is like a dictionary. You can parse - like this:
public void ParseObject()
{
var response = #"{
'meta':{
'status':200,
'message':'success'
},
'data':{
'0':{
'MsgID':'2661689817',
'Status':'6',
'SendTime':'2021-10-3114:30:04',
'DeliverTime':'2021-10-31 14:30:07'
}
}
}";
var responseObj = JsonConvert.DeserializeObject<MetaData>(response);
}
public class MetaData
{
public Meta Meta { get; set; }
public Dictionary<int, Data> Data { get; set; }
}
public class Meta
{
public string Status { get; set; }
public string Message { get; set; }
}
public class Data
{
public string MsgId { get; set; }
public string Status { get; set; }
public string SendTime { get; set; }
}
try using JsonProperty
public class Data
{
[JsonProperty("0") ]
public _0 _0 { get; set; }
}
public class _0
{
public string MsgID { get; set; }
public string Status { get; set; }
public string SendTime { get; set; }
public string DeliverTime { get; set; }
}

Convert Rest API JSON Response into C# object

I have a code REST API response which is json, and parsing to JObject and pulling a value from it. But i am getting the error when parsing to JObject.
Error: "Unexpected character encountered while parsing value: S. Path '', line 0, position 0."
Is there any other way to convert Json string to C# object.
I have the following code:
using Newtonsoft.Json;
using (HttpResponseMessage message = httpclient.GetAsync(folderIdURL).Result)
{
if(message.IsSuccessStatusCode)
{
var dataobjects = message.Content.ReadAsStringAsync();
//dataobjects = "{"id":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/","title":"DQL query results","author":[{"name":"EMC Documentum"}],"updated":"2019-05-02T15:19:52.508+00:00","page":1,"items-per-page":100,"links":[{"rel":"self","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/?dql=SELECT%20r_object_id%2cobject_name%20FROM%20dm_sysobject%20WHERE%20FOLDER%20(%27%2fgbc%2fUS%2fOSA-ATTACHMENT%2f2019%27)"}],"entries":[{"id":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/?dql=SELECT%20r_object_id%2cobject_name%20FROM%20dm_sysobject%20WHERE%20FOLDER%20(%27%2fgbc%2fUS%2fOSA-ATTACHMENT%2f2019%27)&index=0","title":"0b0111738011c114","updated":"2019-05-02T15:19:52.508+00:00","published":"2019-05-02T15:19:52.508+00:00","links":[{"rel":"edit","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c114"}],"content":{"json-root":"query-result","definition":"https://gbc-dev5.cloud.wc.com/DctmRest/repositori es/dmgbsap_crt/types/dm_sysobject","properties":{"r_object_id":"0b0111738011c114","object_name":"04"},"links":[{"rel":"self","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c114"}]}},{"id":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/?dql=SELECT%20r_object_id%2cobject_name%20FROM%20dm_sysobject%20WHERE%20FOLDER%20(%27%2fgbc%2fUS%2fOSA-ATTACHMENT%2f2019%27)&index=1","title":"0b0111738011c115","updated":"2019-05-02T15:19:52.509+00:00","published":"2019-05-02T15:19:52.509+00:00","links":[{"rel":"edit","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c115"}],"content":{"json-root":"query-result","definition":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/types/dm_sysobject","properties":{"r_object_id":"0b0111738011c115","object_name":"05"},"links":[{"rel":"self","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c115"}]}}]}"
JObject responseObj = JObject.Parse(dataobjects.ToString());
String id = (String)responseObj["entries" -->"content"-->"properties"-->"object_name"];
}
}
}
I am expecting the value from (String)responseObject["enteries"]["content"][" properties"]["object_name"]
JObjects are a pain. You could get a sample of the JSON response and paste it into a converter like json2csharp.com. It will generate a class for you which you can then use like so:
Generated Class:
public class MyClass
{
public string SomeProperty { get; set; }
public string AnotherProperty { get; set; }
}
Usage:
if (message.IsSuccessStatusCode)
{
var deserializedObject = JsonConvert.DeserializeObject<MyClass>(response.Content.ReadAsStringAsync().Result);
Console.WriteLine(deserializedObject.SomeProperty);
}
I would suggest to follow those steps:
You need to check that your json is actually a json, because an error says it is not. You can use online tools like this
If possible, avoid JObject and generate real classes. It is not that hard if you know the structure, and you can use another online tools
Modify your code to use classes
so you will have something like:
using System;
using Newtonsoft.Json;
namespace ConsoleApp11
{
class Program
{
public class Message
{
public Enteries enteries { get; set; }
}
public class Enteries
{
public Content content { get; set; }
}
public class Content
{
public Properties properties { get; set; }
}
public class Properties
{
public string object_name { get; set; }
}
static void Main(string[] args)
{
var input = "{\"enteries\":{\"content\":{ \"properties\":{ \"object_name\":\"your value string\"}}}}";
Message msg = JsonConvert.DeserializeObject<Message>(input);
Console.WriteLine(msg?.enteries?.content?.properties?.object_name ?? "no value");
Console.ReadKey();
}
}
}
I hope it helps 😊
Thank you so much for all the help and trips. Finally i am able to get the required value from JSON string.
Here is the Final code json2csharp.com
public class Author
{
public string name { get; set; }
}
public class Link
{
public string rel { get; set; }
public string href { get; set; }
}
public class Link2
{
public string rel { get; set; }
public string href { get; set; }
}
public class Properties
{
public string r_object_id { get; set; }
public string object_name { get; set; }
}
public class Link3
{
public string rel { get; set; }
public string href { get; set; }
}
public class Content
{
public string json_root { get; set; }
public string definition { get; set; }
public Properties properties { get; set; }
public List<Link3> links { get; set; }
}
public class Entry
{
public string id { get; set; }
public string title { get; set; }
public DateTime updated { get; set; }
public DateTime published { get; set; }
public List<Link2> links { get; set; }
public Content content { get; set; }
}
public class RootObject
{
public string id { get; set; }
public string title { get; set; }
public List<Author> author { get; set; }
public DateTime updated { get; set; }
public int page { get; set; }
public int items_per_page { get; set; }
public List<Link> links { get; set; }
public List<Entry> entries { get; set; }
}
Using Newtonsoft.Json
First get the list of entries from the responseObj. Then loop each entries and use LINQ to JSON to get values by property name or index.
You can use Item[Object] index on JObject/JArray and then cast the returned JValue to the type you want
JObject responseObj = JObject.Parse(dataobjects.ToString());
// get JSON result objects into a list
IList<JToken> entries = responseObj ["entries"].Children().ToList();
foreach(JToken entry in entries)
{
string object_name = (string) entry["content"]["properties"]["object_name"];
}

JSON deserializing to C# types

I have got following JSON that should be deserialized to C# class:
{"status":"error","messages":[{"level":"error","key":"InvalidTokenError","dsc":"Invalid
token"}]}
So I have a questions what is the kind of type should be
[{"level":"error","key":"InvalidTokenError","dsc":"Invalid token"}]
?
Is this array, list or class?
You can use json2csharp.com to get the types of the JSON.
JSON:
{"status":"error","messages":[{"level":"error","key":"InvalidTokenError","dsc":"Invalid token"}]}
Here is the classes generated for your JSON:
public class Message
{
public string level { get; set; }
public string key { get; set; }
public string dsc { get; set; }
}
public class RootObject
{
public string status { get; set; }
public List<Message> messages { get; set; }
}
for JSON:
[{"level":"error","key":"InvalidTokenError","dsc":"Invalid token"}]
Type:
public class Message
{
public string level { get; set; }
public string key { get; set; }
public string dsc { get; set; }
}
You can use this site
public class Message
{
public string level { get; set; }
public string key { get; set; }
public string dsc { get; set; }
}
public class RootObject
{
public string status { get; set; }
public List<Message> messages { get; set; }
}

Deserialize Json Object with for each

var serverData = serverConnection.connect("login.php", pairs);
RootObject json = JsonConvert.DeserializeObject<RootObject>(await serverData);
foreach (Logined m in json.logined)
{
}
public class Logined
{
public string id { get; set; }
public string firsname { get; set; }
public string lastname { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string profilePic { get; set; }
public string thumbnail { get; set; }
}
public class RootObject
{
public Logined logined { get; set; }
}
the error in the for each it says cannot operate on variables of type public definition for getenumerator
Your root object contains only a single Logined, so there is nothing to enumerate.
public class RootObject
{
public Logined logined { get; set; } //not a collection
}
foreach (Logined m in json.logined) //json.logined is a single object (not a collection)
{
}
If your server is returning a collection of Logined, you have to change your RootObject definition.
public class RootObject
{
public Logined[] logined { get; set; } //array of Logined
}

Categories