How to deserialize an object and pass it to a response model - c#

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

Related

How to use json.net to Deserialize a nested class?

I have the following class
public class CallbackResultsJson
{
public class CallbackResults
{
public string Status { get; set; }
public string Message { get; set; }
public string Data { get; set; }
public string Log { get; set; }
public string StatusText { get; set; }
public string TransactionToken { get; set; }
}
}
I am trying to use Json.Net to Deserialize requestbody but I am always getting a null for status,data. any ideas why ?
var requestbody =#"
{
"CallbackResults":
{
"TransactionToken":"b65524-qwe",
"Status":0,
"Message":"Publish Application to QaLevel Operation Completed",
"Data":[],
"Log":["sucess"
},
"RequestNumber":"REQ1234"
}"
var TransactionResult = JsonConvert.DeserializeObject<CallbackResultsJson.CallbackResults>(requestBody);
Just a little bit of change should be done.
Your class:
public class CallbackResultsJson
{
public CallbackResultsClass CallbackResults { get; set; }
public string RequestNumber { get; set; }
public class CallbackResultsClass
{
public int Status { get; set; }
public string Message { get; set; }
public string[] Data { get; set; }
public string Log { get; set; }
public string TransactionToken { get; set; }
}
}
Your data:
var requestbody = #"
{
""CallbackResults"":
{
""TransactionToken"":""b65524-qwe"",
""Status"":0,
""Message"":""Publish Application to QaLevel Operation Completed"",
""Data"":[""Data1"", ""Data2""],
""Log"":""sucess""
},
""RequestNumber"":""REQ1234""
}";
var result = JsonConvert.DeserializeObject<CallbackResultsJson>(requestbody);
Your class needs to have a property of the sub-type,
public class CallbackResultsJson
{
public CallBackResults CallbackResults { get; set; }
public string RequestNumber { get; set; )
public class CallbackResults
{
public string Status { get; set; }
public string Message { get; set; }
public string Data { get; set; }
public string Log { get; set; }
public string StatusText { get; set; }
public string TransactionToken { get; set; }
}
}
var result = JsonConvert.DeserializeObject<CallbackResultsJson>(requestBody);
I have used json2csharp.com to convert requestbody to c# classes and it generated these classes.it worked
public class CallbackResults
{
public string TransactionToken { get; set; }
public int Status { get; set; }
public string Message { get; set; }
public List<string> Data { get; set; }
public List<string> Log { get; set; }
}
public class CallbackResultsRootObj
{
public CallbackResults VdiCallbackResults { get; set; }
public string RequestNumber { get; set; }
}
var vdiTransactionResult = JsonConvert.DeserializeObject<CallbackResultsRootObj>(requestBody);

C# Deserialize json api response

hey i want to Deserialize this json API response to get values including profile state etc for processing in the program.
i tried multiple ways from different questions in here but i get response as null.
here is the code, correct me what i am doing wrong please
{
"response": {
"players": [{
"steamid": "xxxxxxxxxxxxxxxxx",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "xxxx xxxx",
"lastlogoff": 1529478555,
"commentpermission": 1,
"profileurl": "xxxxxxxxxxxxxxx",
"avatar": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"avatarmedium": "xxxxxxxxxxxxxxxxxxxxx",
"avatarfull": "xxxxxxxxxxx",
"personastate": 1,
"realname": "xxxx",
"primaryclanid": "xxxxxxxxxx",
"timecreated": 1097464215,
"personastateflags": 0
}]
}
}
The code i tried
public class AccountInfo
{
public string steamid { get; set; }
public int communityvisibilitystate { get; set; }
public int profilestate { get; set; }
public string personaname { get; set; }
public ulong lastlogoff { get; set; }
public int commentpermission { get; set; }
public string profileurl { get; set; }
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public int personastate { get; set; }
public string realname { get; set; }
public string primaryclanid { get; set; }
public ulong timecreated { get; set; }
public int personastateflags { get; set; }
}
public class Response
{
public AccountInfo response { get; set; }
}
public class Response1
{
public Response players { get; set; }
}
static void Main(string[] args)
{
DeserilizeJson();
}
internal static void DeserilizeJson()
{
string json = GetUrlToString("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=xxxxxxxxxxxxxxxxxxxxx&steamids=xxxxxxxxxxxxxxx");
Console.WriteLine(json);
Response1 info = JsonConvert.DeserializeObject<Response1>(json);
using (StreamWriter file = File.CreateText(#"c:\test.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, info);
}
}
internal static string GetUrlToString(string url)
{
String Response = null;
try
{
using (WebClient client = new WebClient())
{
Response = client.DownloadString(url);
}
}
catch (Exception)
{
return null;
}
return Response;
}
Use this as a Model Class
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class JsonModel
{
[JsonProperty("response")]
public Response Response { get; set; }
}
public partial class Response
{
[JsonProperty("players")]
public List<Player> Players { get; set; }
}
public partial class Player
{
[JsonProperty("steamid")]
public string Steamid { get; set; }
[JsonProperty("communityvisibilitystate")]
public long Communityvisibilitystate { get; set; }
[JsonProperty("profilestate")]
public long Profilestate { get; set; }
[JsonProperty("personaname")]
public string Personaname { get; set; }
[JsonProperty("lastlogoff")]
public long Lastlogoff { get; set; }
[JsonProperty("commentpermission")]
public long Commentpermission { get; set; }
[JsonProperty("profileurl")]
public string Profileurl { get; set; }
[JsonProperty("avatar")]
public string Avatar { get; set; }
[JsonProperty("avatarmedium")]
public string Avatarmedium { get; set; }
[JsonProperty("avatarfull")]
public string Avatarfull { get; set; }
[JsonProperty("personastate")]
public long Personastate { get; set; }
[JsonProperty("realname")]
public string Realname { get; set; }
[JsonProperty("primaryclanid")]
public string Primaryclanid { get; set; }
[JsonProperty("timecreated")]
public long Timecreated { get; set; }
[JsonProperty("personastateflags")]
public long Personastateflags { get; set; }
}
Then do this in your Main Class
var info = JsonConvert.DeserializeObject<JsonModel>(json);
var Response = info.Response
Open nuget, search newtonsoft.json and install.
Deserialize:
var deserialized = JsonConvert.DeserializeObject(jsonstring);
Try this:
public class Player
{
public string steamid { get; set; }
public int communityvisibilitystate { get; set; }
public int profilestate { get; set; }
public string personaname { get; set; }
public ulong lastlogoff { get; set; }
public int commentpermission { get; set; }
public string profileurl { get; set; }
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public int personastate { get; set; }
public string realname { get; set; }
public string primaryclanid { get; set; }
public ulong timecreated { get; set; }
public int personastateflags { get; set; }
}
public class Response
{
public Player[] players { get; set; }
}
public class EncapsulatedResponse
{
public Response response {get;set;}
}
internal static void DeserilizeJson()
{
string json = GetUrlToString("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=xxxxxxxxxxxxxxxxxxxxx&steamids=xxxxxxxxxxxxxxx");
Console.WriteLine(json);
EncapsulatedResponse info = JsonConvert.DeserializeObject<EncapsulatedResponse>(json);
using (StreamWriter file = File.CreateText(#"c:\test.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, info);
}
}
The players property should be a list of players as it is an array . Below is the Correct Model
public class Player
{
public string steamid { get; set; }
public int communityvisibilitystate { get; set; }
public int profilestate { get; set; }
public string personaname { get; set; }
public int lastlogoff { get; set; }
public int commentpermission { get; set; }
public string profileurl { get; set; }
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public int personastate { get; set; }
public string realname { get; set; }
public string primaryclanid { get; set; }
public int timecreated { get; set; }
public int personastateflags { get; set; }
}
public class Response
{
public List<Player> players { get; set; }
}
You need to change the object structure:
public class Response
{
public AccountInfo[] players { get; set; }
}
public class Response1
{
public Response response { get; set; }
}
then deserialize Response1 (like u do currently)
Just to provide a different approach, you can use JObject (Newtonsoft.Json.Linq) so that you only need the AccountInfo class:
var accounts = JObject.Parse(json).Root
.SelectToken("response.players")
.ToObject(typeof(AccountInfo[]));
Or in some cases, it is even easier just navigating the properties:
var accounts = JObject.Parse(json)["response"]["players"]
.ToObject((typeof(AccountInfo[])));

Response is null when I used Restsharp library's GET request to access Json data

I am using Restsharp library to do Webservice operations.I tried to access data from the link(http://www.mocky.io/v2/595616d92900003d02cd7191) and print it in Console but I am not getting any response.When I used breakpoints,Response is showing null.Here's my code to get data from the link.
private async void GetItemsFromJSON()
{
IRestClient client = new RestClient("http://www.mocky.io/v2/595616d92900003d02cd7191");
IRestRequest request = new RestRequest(Method.GET);
request.RequestFormat = DataFormat.Json;
try
{
await Task.Run(() =>
{
IRestResponse<List<ItemDetails>> response = client.Execute<List<ItemDetails>>(request);
var Items = SimpleJson.DeserializeObject<ItemDetails>(response.Content);
Console.WriteLine(response.Content);
}
public class ItemDetails
{
public List<Itemschema> items { get; set; }
}
public class Itemschema
{
public int id { get; set; }
public string sku { get; set; }
public string name { get; set; }
public int attribute_set_id { get; set; }
public int price { get; set; }
public int status { get; set; }
public int visibility { get; set; }
public string type_id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public int weight { get; set; }
}
Am I missing something here?My schema class which corresponds to the Json data is shown above.
I suspect that:
IRestResponse<List<ItemDetails>> response = client.Execute<List<ItemDetails>>(request);
should be:
IRestResponse<ItemDetails> response = client.Execute<ItemDetails>(request);
http://www.mocky.io/v2/595616d92900003d02cd7191 seems to return an items property which contains an array of schemas. That maps closer to ItemDetails than List<ItemDetails>.
This complete sample works, so you may want to compare it with your code:
using System;
using System.Collections.Generic;
using RestSharp;
namespace Test
{
public class ItemDetails
{
public List<Itemschema> items { get; set; }
}
public class Itemschema
{
public int id { get; set; }
public string sku { get; set; }
public string name { get; set; }
public int attribute_set_id { get; set; }
public int price { get; set; }
public int status { get; set; }
public int visibility { get; set; }
public string type_id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public int weight { get; set; }
}
public class Program
{
static void Main(string[] args)
{
IRestClient client = new RestClient("http://www.mocky.io/v2/595616d92900003d02cd7191");
IRestRequest request = new RestRequest(Method.GET);
request.RequestFormat = DataFormat.Json;
IRestResponse<ItemDetails> response = client.Execute<ItemDetails>(request);
var Items = SimpleJson.DeserializeObject<ItemDetails>(response.Content);
Console.WriteLine(Items.items.Count);
Console.ReadLine();
}
}
}

Unable To Parse JSON Response in C#

I am trying to parse a whois json response but when I try parse it I get null values.
string html;
string whoisUrl = "https://whois.apitruck.com/:google.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(whoisUrl);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
{
html = reader.ReadToEnd();
}
}
Class1 m = JsonConvert.DeserializeObject<Class1>(html);
MessageBox.Show(m.created);
Object
class Class1
{
public string created { get; set; }
}
can anyone please point what I am doing wrong here ?
Your Class1 doesn't get the value since "created" is part of the "response" and not the root level of the JSON reponse.
You'll either need to use dynamic or create a hierarchy for the classes for a simple fix.
class Class1
{
public Response Response { get; set; }
}
class Response
{
public string created { get; set; }
}
Then you can use this:
Class1 m = JsonConvert.DeserializeObject<Class1>(html);
MessageBox.Show(m.Response.created);
UPDATE
Also, here's an example of how to use the dynamic:
var m = JsonConvert.DeserializeObject<dynamic>(html);
DateTime created = (DateTime)m.response.created;
There is nice app to convert json to .net class:
public class Registrar
{
public string id { get; set; }
public string name { get; set; }
public object email { get; set; }
public string url { get; set; }
}
public class Response
{
public string name { get; set; }
public string idnName { get; set; }
public List<string> status { get; set; }
public List<string> nameserver { get; set; }
public object ips { get; set; }
public string created { get; set; }
public string changed { get; set; }
public string expires { get; set; }
public bool registered { get; set; }
public bool dnssec { get; set; }
public string whoisserver { get; set; }
public List<object> contacts { get; set; }
public Registrar registrar { get; set; }
public List<string> rawdata { get; set; }
public object network { get; set; }
public object exception { get; set; }
public bool parsedContacts { get; set; }
}
public class RootObject
{
public int error { get; set; }
public Response response { get; set; }
}
...
RootObject result = JsonConvert.DeserializeObject<RootObject>(html);
var created = result.response.created;

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