I'm expecting this response from the API:
{
"EnterKey":"9876546789039876543567890",
"Id":1441462,
"Category":null,
"job":{
"Id":1020332,
"SortName":"test"
},
"Initiator":null,
"Source":{
"Id":1,
"Description":"data"
},
"BalanceNow":0.0,
"ready":false,
"Others":[
{
"Id":1255080,
"Amount":100.0,
"JobMethod":{
"Id":24,
"Description":"task",
"JobType":{
"Id":1,
"Description":"Other"
}
},
"Notes":null
}
],
"Messages":null,
"Products":[
{
"Tasks":{
"Id":2,
"Description":"Blah..."
},
"Join":null,
"TargetData":{
"PaymentId":1535026,
"WantedNotes":"Looks good",
"Name":"John"
},
"AdminDefinedFee":null,
"Product":"New"
}
]
}
I want to deserialize the above Json Response to get the WantedNotes from TargetData that is inside Products. I wanted it done with Json.NET so i tried doing:
public class datasummary
{
public List<TargetData> Products { get; set; }
}
public class TargetData
{
public string WantedNotes { get; set; }
}
var myresult = JsonConvert.DeserializeObject<datasummary>(jsonresponse);
That don't work. I don't know how that really is done. Can someone please show it's done correct?
Define the class structure like this:
public class Job
{
public int Id { get; set; }
public string SortName { get; set; }
}
public class Source
{
public int Id { get; set; }
public string Description { get; set; }
}
public class JobType
{
public int Id { get; set; }
public string Description { get; set; }
}
public class JobMethod
{
public int Id { get; set; }
public string Description { get; set; }
public JobType JobType { get; set; }
}
public class Others
{
public int Id { get; set; }
public double Amount { get; set; }
public JobMethod JobMethod { get; set; }
public object Notes { get; set; }
}
public class Tasks
{
public int Id { get; set; }
public string Description { get; set; }
}
public class TargetData
{
public int PaymentId { get; set; }
public string WantedNotes { get; set; }
public string Name { get; set; }
}
public class Product
{
public Tasks Tasks { get; set; }
public object Join { get; set; }
public TargetData TargetData { get; set; }
public object AdminDefinedFee { get; set; }
public string Product { get; set; }
}
public class DataDummary
{
public string EnterKey { get; set; }
public int Id { get; set; }
public object Category { get; set; }
public Job job { get; set; }
public object Initiator { get; set; }
public Source Source { get; set; }
public double BalanceNow { get; set; }
public bool ready { get; set; }
public List<Others> Others { get; set; }
public object Messages { get; set; }
public List<Product> Products { get; set; }
}
Then use:
var myresult = JsonConvert.DeserializeObject < DataSummary > (jsonresponse);
When working with json, you can copy all text from the file, add an new class then go to
Edit > Paste Especial > Paste JSON as Classes.
It will do all the work for you
Then you can use
var myresult = JsonConvert.DeserializeObject <DataSummary> (jsonresponse);
Related
This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
Closed 5 years ago.
I am trying to parse JSON response using newtownsoft.json trying to parse the followers count and writeline.
This is the code:
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
namespace J2C
{
class Checker
{
static void Main(string[] args)
{
var client = new WebClient();
var text = client.DownloadString("https://www.instagram.com/2saleapp/?__a=1");
User userObject = JsonConvert.DeserializeObject<User>(text);
Console.WriteLine("Followers count =" + userObject.followed_by);
Console.ReadKey();
}
}
}
and this is the API response:
{
"user": {
"biography": "Install 2Sale app to post your AD instantly!\nSnap, post, and sell. Its time to sale.",
"blocked_by_viewer": false,
"country_block": false,
"external_url": "http://autoigs.com/2sale_install",
"external_url_linkshimmed": "http://l.instagram.com/?u=http%3A%2F%2Fautoigs.com%2F2sale_install&e=ATMoKdz87_iz044M0ebrfU95WQT7JqBpnlGiGH9UDOsn7dRax7G6ZMxjh7wMuHY",
"followed_by": {
"count": 6511
},
"followed_by_viewer": false,
"follows": {
"count": 19
},
I just want to WriteLine Followed_by count numbers.
Any one can help me?
thank you
Copy the raw json to the clipboard. In Visual Studio menu select Edit > Paste Special > Paste JSON As Classes (this item is present at least since version VS2015. For earlier versions see). This will generate a set of classes.
public class Rootobject
{
public User user { get; set; }
public string logging_page_id { get; set; }
}
public class User
{
public string biography { get; set; }
public bool blocked_by_viewer { get; set; }
public bool country_block { get; set; }
public string external_url { get; set; }
public string external_url_linkshimmed { get; set; }
public Followed_By followed_by { get; set; }
public bool followed_by_viewer { get; set; }
public Follows follows { get; set; }
public bool follows_viewer { get; set; }
public string full_name { get; set; }
public bool has_blocked_viewer { get; set; }
public bool has_requested_viewer { get; set; }
public string id { get; set; }
public bool is_private { get; set; }
public bool is_verified { get; set; }
public string profile_pic_url { get; set; }
public string profile_pic_url_hd { get; set; }
public bool requested_by_viewer { get; set; }
public string username { get; set; }
public object connected_fb_page { get; set; }
public Media media { get; set; }
}
public class Followed_By
{
public int count { get; set; }
}
public class Follows
{
public int count { get; set; }
}
public class Media
{
public Node[] nodes { get; set; }
public int count { get; set; }
public Page_Info page_info { get; set; }
}
public class Page_Info
{
public bool has_next_page { get; set; }
public string end_cursor { get; set; }
}
public class Node
{
public string __typename { get; set; }
public string id { get; set; }
public bool comments_disabled { get; set; }
public Dimensions dimensions { get; set; }
public object gating_info { get; set; }
public string media_preview { get; set; }
public Owner owner { get; set; }
public string thumbnail_src { get; set; }
public object[] thumbnail_resources { get; set; }
public bool is_video { get; set; }
public string code { get; set; }
public int date { get; set; }
public string display_src { get; set; }
public string caption { get; set; }
public Comments comments { get; set; }
public Likes likes { get; set; }
public int video_views { get; set; }
}
public class Dimensions
{
public int height { get; set; }
public int width { get; set; }
}
public class Owner
{
public string id { get; set; }
}
public class Comments
{
public int count { get; set; }
}
public class Likes
{
public int count { get; set; }
}
Next, use the Rootobject. It's supposed to work.
var client = new WebClient();
var text = client.DownloadString("https://www.instagram.com/2saleapp/?__a=1");
Rootobject rootObject = JsonConvert.DeserializeObject<Rootobject>(text);
Console.WriteLine("Followers count =" + rootObject.user.followed_by.count);
In general, you should change the naming to conform to the generally accepted naming rules. You should use the JsonProperty attribute.
public class Rootobject
{
[JsonProperty("user")]
public User User { get; set; }
[JsonProperty("logging_page_id")]
public string LoggingPageId { get; set; }
}
And so on.
Create a class with name User in order to deserialize json string to User.
public class User
{
public string biography { get; set; }
public bool blocked_by_viewer { get; set; }
public bool country_block { get; set; }
public string external_url { get; set; }
public string external_url_linkshimmed { get; set; }
public FollowedBy followed_by { get; set; }
public string followed_by_viewer { get; set; }
public Follow follows { get; set; }
}
public class FollowedBy
{
public int count { get; set; }
}
public class Follow
{
public int count { get; set; }
}
After getting json string result using the below line for DeserializeObject to User and then assign it to new User object , after that use userObject for showing result.
User userObject = JsonConvert.DeserializeObject<User>(jsonString);
Now you have a user object that fill property with the API response.
How would I parse this response using C#?
[
{
"date":"2016-10-01",
"stats":[
{
"type":"subuser",
"name":"coolguy#yahoo.com",
"metrics":{
"blocks":23,
"bounce_drops":164,
"bounces":19,
"clicks":0,
"deferred":412,
"delivered":3435,
"invalid_emails":27,
"opens":0,
"processed":3481,
"requests":3675,
"spam_report_drops":3,
"spam_reports":0,
"unique_clicks":0,
"unique_opens":0,
"unsubscribe_drops":0,
"unsubscribes":0
}
}
]
},
{
"date":"2016-10-02",
"stats":[
{
"type":"subuser",
"name":"coolguy#yahoo.com",
"metrics":{
"blocks":0,
"bounce_drops":0,
"bounces":0,
"clicks":0,
"deferred":95,
"delivered":0,
"invalid_emails":0,
"opens":0,
"processed":0,
"requests":0,
"spam_report_drops":0,
"spam_reports":0,
"unique_clicks":0,
"unique_opens":0,
"unsubscribe_drops":0,
"unsubscribes":0
}
}
]
}
]
Using JsonConvert deserialize it to dynamic as below or create a matching class structure and deserialize it to that.
using Newtonsoft.Json;
.....
string json = File.ReadAllText("data.txt");
var deserializedData = JsonConvert.DeserializeObject<dynamic>(json);
Using json2csharp your classes should look like:
public class Metrics
{
public int blocks { get; set; }
public int bounce_drops { get; set; }
public int bounces { get; set; }
public int clicks { get; set; }
public int deferred { get; set; }
public int delivered { get; set; }
public int invalid_emails { get; set; }
public int opens { get; set; }
public int processed { get; set; }
public int requests { get; set; }
public int spam_report_drops { get; set; }
public int spam_reports { get; set; }
public int unique_clicks { get; set; }
public int unique_opens { get; set; }
public int unsubscribe_drops { get; set; }
public int unsubscribes { get; set; }
}
public class Stat
{
public string type { get; set; }
public string name { get; set; }
public Metrics metrics { get; set; }
}
public class RootObject
{
public string date { get; set; }
public List<Stat> stats { get; set; }
}
These generated classes can be improved - for example not storing the date in a string but a DateTime
string json = File.ReadAllText("data.txt");
RootObject deserializedData = JsonConvert.DeserializeObject<RootObject>(json);
How to put the items in a JSON string in a WPF grid?
{
"success":"true",
"response":{
"Page":1,
"PageFirst":1,
"PageLast":1,
"PageRecordFirst":1,
"PageRecordLast":2147483647,
"PageSize":2147483647,
"RecordCount":2,
"ResultSet":[
{
"CompanyId":1,
"CompanyName":"Focus",
"ComputedProjectProgressAll":39.000000,
"ComputedProjectProgressCurrent":39.000000,
"ComputedProjectProgressExpected":86.00,
"ComputedTaskCountAll":434,
"ComputedTaskCountCurrent":354,
"CreateDate":"\/Date(1421947846600-0800)\/",
"CreateUserId":1,
"CreateUserName":"MobiCloud Admin",
"CustomerId":1,
"CustomerName":"MobiCloud",
"Description":"Obra 001",
"Id":7,
"IsActive":true,
"ModifyDate":"\/Date(1421947846600-0800)\/",
"ModifyUserId":1,
"ModifyUserName":"MobiCloud Admin",
"Name":"Obra Desenv 001",
"Status":0
},
{
"CompanyId":1,
"CompanyName":"Focus",
"ComputedProjectProgressAll":69.000000,
"ComputedProjectProgressCurrent":69.000000,
"ComputedProjectProgressExpected":100.00,
"ComputedTaskCountAll":199,
"ComputedTaskCountCurrent":199,
"CreateDate":"\/Date(1422298868660-0800)\/",
"CreateUserId":1,
"CreateUserName":"MobiCloud Admin",
"CustomerId":1,
"CustomerName":"MobiCloud",
"Description":"sadasdsad",
"Id":8,
"IsActive":true,
"ModifyDate":"\/Date(1422298868660-0800)\/",
"ModifyUserId":1,
"ModifyUserName":"MobiCloud Admin",
"Name":"Obra Desenv 002",
"Status":0
}
]
}
}
First of all you need to create a c# class equivalent to JSON. use http://json2csharp.com/ to create c# class. Then you need to deserialize your JSON string use JSON.NET from http://json.codeplex.com/. Now you have got all the things setup. Now you can assing these data into WPF controls. I have assigned the response resultset into one datagrid. Refer the below code.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LoadData();
}
private void LoadData()
{
string str = File.ReadAllText("1.txt");
RootObject deserializedObject = JsonConvert.DeserializeObject<RootObject>(str);
dgr.ItemsSource = deserializedObject.response.ResultSet;
}
}
public class ResultSet
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public double ComputedProjectProgressAll { get; set; }
public double ComputedProjectProgressCurrent { get; set; }
public double ComputedProjectProgressExpected { get; set; }
public int ComputedTaskCountAll { get; set; }
public int ComputedTaskCountCurrent { get; set; }
public DateTime CreateDate { get; set; }
public int CreateUserId { get; set; }
public string CreateUserName { get; set; }
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public string Description { get; set; }
public int Id { get; set; }
public bool IsActive { get; set; }
public DateTime ModifyDate { get; set; }
public int ModifyUserId { get; set; }
public string ModifyUserName { get; set; }
public string Name { get; set; }
public int Status { get; set; }
}
public class Response
{
public int Page { get; set; }
public int PageFirst { get; set; }
public int PageLast { get; set; }
public int PageRecordFirst { get; set; }
public long PageRecordLast { get; set; }
public long PageSize { get; set; }
public int RecordCount { get; set; }
public List<ResultSet> ResultSet { get; set; }
}
public class RootObject
{
public string success { get; set; }
public Response response { get; set; }
}
<Grid>
<DataGrid x:Name="dgr"/>
</Grid>
So I have a set of classes:
public class CallQueueRequest
{
public string ACK { get; set; }
public string ERROR { get; set; }
public Agent AGENT { get; set; }
public Skill SKILL { get; set; }
public string TIME { get; set; }
}
public class Agent
{
public string has_result { get; set; }
public List<Agents> agents { get; set; }
}
public class Agents
{
public string display_name { get; set; }
public string time_in_state { get; set; }
public string state { get; set; }
public string callstakentoday { get; set; }
public string avaya_skill_num { get; set; }
}
public class Skill
{
public string has_result { get; set; }
public string num_skills { get; set; }
public List<Skills> skills { get; set; }
}
public class Skills
{
public string display_name { get; set; }
public string avaya_skill_num { get; set; }
public string callsinqueue { get; set; }
public string callstoday { get; set; }
public string abantoday { get; set; }
public string lwt { get; set; }
public string ewt { get; set; }
public string servicelvl { get; set; }
public string avgspeedans { get; set; }
public string talktime { get; set; }
}
And I have this Json:
{
"ACK":"SUCCESS",
"ERROR":null,
"AGENT":{
"has_results":1,
"agents":[
{
"display_name":"John Doe",
"time_in_state":"378",
"state":"Acd",
"callstakentoday":null,
"avaya_skill_num":"81"
},
{
"display_name":"Jane Joe",
"time_in_state":"220",
"state":"Acd",
"callstakentoday":null,
"avaya_skill_num":"81"
}
]
},
"SKILL":{
"has_results":1,
"num_skills":1,
"skills":[
{
"display_name":"QueueName",
"avaya_skill_num":"81",
"callsinqueue":"1",
"callstoday":"29",
"abandtoday":"1",
"lwt":"74",
"ewt":"223",
"servicelvl":"86",
"avgspeedans":"35",
"talktime":"873"
}
]
},
"TIME":1355864270
}
I am using this code:
object qr = JsonConvert.DeserializeObject(jsonString);
This does not seem to be converting from Json to the complex class properly. Can someone assist me with this? I think its just a small mistake.
I was able to find some info on what I'm trying to do. If anyone finds this question, here is the answer
I have a JSON object like the following
{
"data": [
{
"id": "18128270850211_49239570772655",
"from": {
"name": "Someone Unimportant",
"id": "57583427"
}
/* more stuff */
}
]
}
I want to parse it using JSON.NET,
FacebookResponse<FacebookPost> response = JsonConvert.DeserializeObject<FacebookResponse<FacebookPost>>(json);
internal class FacebookResponse<T> where T : class
{
public IList<T> Data { get; set; }
public FacebookResponsePaging Paging { get; set; }
}
public class FacebookPost
{
public string Id { get; set; }
[JsonProperty("to.data.id")]
public string FeedId { get; set; }
[JsonProperty("from.id")]
public string UserId { get; set; }
[JsonProperty("created_time")]
public DateTime CreatedTime { get; set; }
[JsonProperty("updated_time")]
public DateTime UpdatedTime { get; set; }
public string Type { get; set; } // TODO: Type enum??
public string Message { get; set; }
public string Link { get; set; }
public string Name { get; set; }
public string Caption { get; set; }
public string Description { get; set; }
}
Everything comes through except for the FeedId and the UserId properties. How should I be mapping these?
public class From
{
public string name { get; set; }
public string id { get; set; }
}
public class Datum
{
public string id { get; set; }
public From from { get; set; }
}
public class FacebookPost
{
public List<Datum> data { get; set; }
}
internal class FacebookResponse<T> where T : class
{
public IList<T> Data { get; set; }
public FacebookResponsePaging Paging { get; set; }
}
FacebookResponse<FacebookPost> response = JsonConvert.DeserializeObject<FacebookResponse<FacebookPost>>(json);
Try below code :)
Use this site to get the object for .net
Then you can use JSON.Net to deserialize: ex.JsonConvert.DeserializeObject(input) iirc