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
Related
Using C#, Newtonsoft.Json 13.0.2 and having the following possible JSONs:
Json type 1 ---------------------
{
"type": "succeeded",
"event_date": "2023",
"transaction": {
"id": "AAA",
"authorization": "123",
"operation_type": "456"
}
}
Json type 2 ---------------------
{
"type": "failed",
"event_date": "2023",
"failureReport": {
"id": "AAA",
"failureType": "123"
}
}
I'm using the following code to deserialize any of the two objects as follows:
[Table("MySql_Test_Table")]
public class TestClass
{
[Key]
[JsonPropertyName("id")]
public int id { get; set; }
[JsonPropertyName("event_date")]
public DateTime? event_date { get; set; }
[JsonPropertyName("type")]
public String? type { get; set; }
[JsonPropertyName("transaction.id")]
public String? transaction_id { get; set; }
[JsonPropertyName("transaction.authorization")]
public String? authorization{ get; set; }
[JsonPropertyName("transaction.operation_type")]
public String? operation_type{ get; set; }
[JsonPropertyName("failureReport.id")]
public String? failureReportId{ get; set; }
[JsonPropertyName("failureReport.failureType")]
public String? failureReportType{ get; set; }
}
TestClass testClass = Newtonsoft.Json.JsonConvert.DeserializeObject<TestClass>(oneOfTwoPossiblejsonTexts.ToString());
//...Code for saving testClass using EntityFramrwork...
With the aforementioned code I'm able to get the values for type and event_date without problem. However I'm unable to populate id, authorization, operation_type, failureReportId, orfailureReportType.
I guess the problem is my [JsonPropertyName] tag. Please, how could I correct it to access the required values?
Likely, the safest bet is to create corresponding C# types:
public class TestClass
{
[Key]
[JsonPropertyName("id")]
public int id { get; set; }
[JsonPropertyName("event_date")]
public DateTime? event_date { get; set; }
[JsonPropertyName("type")]
public String? type { get; set; }
public TransactionType Transaction { get; set; }
public FailureReportType FailureReport { get; set; }
}
public class TransactionType
{
[JsonPropertyName("id")]
public String? transaction_id { get; set; }
[JsonPropertyName("authorization")]
public String? authorization{ get; set; }
[JsonPropertyName("operation_type")]
public String? operation_type{ get; set; }
}
public class FailureReportType
{
[JsonPropertyName("id")]
public String? failureReportId{ get; set; }
[JsonPropertyName("failureType")]
public String? failureReportType{ get; set; }
}
if you want to deserialize these jsons to your flatten class, you can create a JsonConstructor
public class TestClass
{
public int id { get; set; }
[JsonProperty("event_date")]
public string? eventDate { get; set; }
public String? type { get; set; }
public String? transactionId { get; set; }
public String? authorization { get; set; }
public String? operationType { get; set; }
public String? failureReportId { get; set; }
public String? failureReportType { get; set; }
[JsonConstructor]
public TestClass(JToken transaction, JToken failureReport)
{
if (transaction != null)
{
transactionId = (string?)transaction["id"];
authorization = (string?)transaction["authorization"];
operationType = (string?)transaction["operation_type"];
};
if (failureReport != null)
{
failureReportId = (string?)failureReport["id"];
failureReportType = (string?)failureReport["failureType"];
};
}
public TestClass() { }
}
and since you are using Newtonsoft.Json for deserialization, you have to use [JsonProperty] instead of [JsonPropertyName]
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);
New to C# and JSON but basically I have to use a C# script component in SSIS to extract data from a web service. I was able to do it initially with a different JSON format but this one includes an array.
I get the following error:
"Type 'Rootobject' is not supported for deserialization of an array."
Below is how I call the Deserializer:
//Deserialize our JSON
JavaScriptSerializer sr = new
jsonResponse = sr.Deserialize<Rootobject>(responseFromServer);
Here is my JSON structure (not quite all since fairly large):
[
{
"status":"SUCCESS",
"object":{
"responseStatusCode":0,
"productId":"35100003",
"cansimId":"251-0008",
"cubeTitleEn":"Average counts of young persons in provincial and territorial correctional services",
"cubeTitleFr":"Comptes moyens des adolescents dans les services correctionnels provinciaux et territoriaux",
"cubeStartDate":"1997-01-01",
"cubeEndDate":"2017-01-01",
"frequencyCode":12,
"nbSeriesCube":174,
"nbDatapointsCube":3468,
"releaseTime":"2019-05-09T08:30",
"archiveStatusCode":"2",
"archiveStatusEn":"CURRENT - a cube available to the public and that is current",
"archiveStatusFr":"ACTIF - un cube qui est disponible au public et qui est toujours mise a jour",
"subjectCode":[
"350102",
"4211"
],
"surveyCode":[
"3313"
],
"dimension":[ ],
"footnote":[ ],
"correction":[
]
}
}
]
Finally here is my Class structure obtained through Paste Special in Visual Studio:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string status { get; set; }
public Object _object { get; set; }
}
public class Object
{
public int responseStatusCode { get; set; }
public string productId { get; set; }
public string cansimId { get; set; }
public string cubeTitleEn { get; set; }
public string cubeTitleFr { get; set; }
public string cubeStartDate { get; set; }
public string cubeEndDate { get; set; }
public int frequencyCode { get; set; }
public int nbSeriesCube { get; set; }
public int nbDatapointsCube { get; set; }
public string releaseTime { get; set; }
public string archiveStatusCode { get; set; }
public string archiveStatusEn { get; set; }
public string archiveStatusFr { get; set; }
public string[] subjectCode { get; set; }
public string[] surveyCode { get; set; }
public Dimension[] dimension { get; set; }
public Footnote[] footnote { get; set; }
public object[] correction { get; set; }
}
public class Dimension
{
public int dimensionPositionId { get; set; }
public string dimensionNameEn { get; set; }
public string dimensionNameFr { get; set; }
public bool hasUom { get; set; }
public Member[] member { get; set; }
}
public class Member
{
public int memberId { get; set; }
public int? parentMemberId { get; set; }
public string memberNameEn { get; set; }
public string memberNameFr { get; set; }
public string classificationCode { get; set; }
public string classificationTypeCode { get; set; }
public int? geoLevel { get; set; }
public int? vintage { get; set; }
public int terminated { get; set; }
public int? memberUomCode { get; set; }
}
public class Footnote
{
public int footnoteId { get; set; }
public string footnotesEn { get; set; }
public string footnotesFr { get; set; }
public Link link { get; set; }
}
public class Link
{
public int footnoteId { get; set; }
public int dimensionPositionId { get; set; }
public int memberId { get; set; }
}
I know the problem lies within how I call the Deserialize<Rootobject> and different data types but I wasn't able to find the solution. Any suggestions are appreciated.
AV
Try deserializing directly to a list of Class1.
jsonResponse = sr.Deserialize<List<Class1>>(responseFromServer);
Also, don't use Object as your class name. That's a really bad practice.
You can control how JSON.NET serializes/deserializes a property as shown here: How can I change property names when serializing with Json.net?
e.g.
[JsonProperty(PropertyName = "object")]
public class MyObject
{
}
I'm working with OneDrive and need to get information about a folders contents back from the server. This is the type of data I am working with:
{
"data": [
{
"id": "folder.xxxx",
"from": {
"name": "john doe",
"id": "xxxx"
},
"name": "Files that are in a folder",
"description": "",
"parent_id": "folder.xxxx",
"size": 0,
"upload_location": "https://apis.live.net/v5.0/folder.xxxx/files/",
"comments_count": 0,
"comments_enabled": false,
"is_embeddable": true,
"count": 0,
"link": "xxxx",
"type": "folder",
"shared_with": {
"access": "Just me"
},
"created_time": "2014-03-06T18:48:16+0000",
"updated_time": "2014-03-06T18:48:16+0000",
"client_updated_time": "2014-03-06T18:48:16+0000"
}, {
"id": "file.xxxx",
(same as above for rest of data structure)
}, {
"id": "file.xxxx",
(Same as above for rest of data structure)
}
]
}
When doing a different request to the server you get back just the ("id" : "folder.xxx") info chunk and I was able to process that data using a class that looks like this:
[DataContract]
public class ResponseFolder
{
[DataMember(Name = "id")]
public string id { get; set; }
[DataMember(Name = "from")]
public from from { get; set; }
[DataMember(Name = "name")]
public string name { get; set; }
//etc.
And handling the entries like "from" with similar structures:
[DataContract]
public class from
{
public string name { get; set; }
public string id { get; set; }
}
I thought I could do the same for the data request at the top and so have this class which is not working for me:
[DataContract]
public class FolderRequest
{
[DataMember(Name = "data")]
public ResponseFolder data { get; set; }
}
And I try to use it on this line:
FolderRequest = jss.Deserialize<FolderRequest>(json);
But FolderRequest is null after that. I have also tried doing
jss.Deserialize<List<ResponseFolder>>(json);
after googling around how to handle arrays in json but that did not work either.
Any help would be appreciated!
Your complete model is
public class From
{
public string name { get; set; }
public string id { get; set; }
}
public class SharedWith
{
public string access { get; set; }
}
public class ResponseFolder
{
public string id { get; set; }
public From from { get; set; }
public string name { get; set; }
public string description { get; set; }
public string parent_id { get; set; }
public int size { get; set; }
public string upload_location { get; set; }
public int comments_count { get; set; }
public bool comments_enabled { get; set; }
public bool is_embeddable { get; set; }
public int count { get; set; }
public string link { get; set; }
public string type { get; set; }
public SharedWith shared_with { get; set; }
public string created_time { get; set; }
public string updated_time { get; set; }
public string client_updated_time { get; set; }
}
public class FolderRequest
{
public List<ResponseFolder> data { get; set; }
}
and you should serialize as
var obj = new JavaScriptSerializer().Deserialize<FolderRequest>(DATA);
Looks like data needs to be an array:
[DataContract]
public class FolderRequest
{
[DataMember(Name = "data")]
public ResponseFolder[] data { get; set; }
}
If you are ok with use Json.Net (http://james.newtonking.com/json), try this:
public class From
{
public string Name { get; set; }
public string Id { get; set; }
}
public class SharedWith
{
[JsonProperty(PropertyName = "access")]
public string AccessName { get; set; }
}
public class ResponseFolder
{
public string Id { get; set; }
public From From { get; set; }
public string Name { get; set; }
public string Description { get; set; }
[JsonProperty(PropertyName = "shared_with")]
public SharedWith SharedWith { get; set; }
}
public class RootObject
{
public List<ResponseFolder> data { get; set; }
}
And then your deserialization:
var result = JsonConvert.DeserializeObject<RootObject>(json);
Hope this helps.
Lets say i have a string that looks like this
{
"_links": {
"next": "https://api.twitch.tv/kraken/users/test_user1/follows/channels?direction=DESC&limit=25&offset=25",
"self": "https://api.twitch.tv/kraken/users/test_user1/follows/channels?direction=DESC&limit=25&offset=0"
},
"follows": [
{
"created_at": "2013-06-02T09:38:45Z",
"_links": {
"self": "https://api.twitch.tv/kraken/users/test_user1/follows/channels/test_channel"
},
"channel": {
"banner": null,
"_id": 1,
"url": "http://www.twitch.tv/test_channel",
"mature": null,
"teams": [
],
"status": null,
"logo": null,
"name": "test_channel",
"video_banner": null,
"display_name": "test_channel",
"created_at": "2007-05-22T10:37:47Z",
"delay": 0,
"game": null,
"_links": {
"stream_key": "https://api.twitch.tv/kraken/channels/test_channel/stream_key",
"self": "https://api.twitch.tv/kraken/channels/test_channel",
"videos": "https://api.twitch.tv/kraken/channels/test_channel/videos",
"commercial": "https://api.twitch.tv/kraken/channels/test_channel/commercial",
"chat": "https://api.twitch.tv/kraken/chat/test_channel",
"features": "https://api.twitch.tv/kraken/channels/test_channel/features"
},
"updated_at": "2008-02-12T06:04:29Z",
"background": null
}
},
...
]
}
The part in channel is gonna appear x amount of times with the "name" part having a different value. How would I, using regex or not get the value in "name" that in the code above has a value of "test_channel". All times that it appears and then print it to a textbox
The only part I think I've managed is the regex part
string regex = #"(""name"":)\s+(\w+)(,""video_banner"")";
Using Json.Net and this site
var obj = JsonConvert.DeserializeObject<Krysvac.RootObject>(yourJsonString);
foreach(var item in obj.follows)
{
Console.WriteLine(item.channel.name);
}
public class Krysvac
{
public class Links
{
public string next { 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 self { get; set; }
public string videos { get; set; }
public string commercial { get; set; }
public string chat { get; set; }
public string features { get; set; }
}
public class Channel
{
public object banner { get; set; }
public int _id { get; set; }
public string url { get; set; }
public object mature { get; set; }
public List<object> teams { get; set; }
public object status { get; set; }
public object logo { get; set; }
public string name { get; set; }
public object video_banner { get; set; }
public string display_name { get; set; }
public string created_at { get; set; }
public int delay { get; set; }
public object game { get; set; }
public Links3 _links { get; set; }
public string updated_at { get; set; }
public object background { get; set; }
}
public class Follow
{
public string created_at { get; set; }
public Links2 _links { get; set; }
public Channel channel { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public List<Follow> follows { get; set; }
}
}
If you don't want to declare these classes, you can use dynamic keyword too
dynamic obj = JsonConvert.DeserializeObject(yourJsonString);
foreach(var item in obj.follows)
{
Console.WriteLine(item.channel.name);
}
If you build classes for your input string like the following using json2csharp.com, you'll get the following classes:
public class Links
{
public string next { 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 self { get; set; }
public string videos { get; set; }
public string commercial { get; set; }
public string chat { get; set; }
public string features { get; set; }
}
public class Channel
{
public object banner { get; set; }
public int _id { get; set; }
public string url { get; set; }
public object mature { get; set; }
public List<object> teams { get; set; }
public object status { get; set; }
public object logo { get; set; }
public string name { get; set; }
public object video_banner { get; set; }
public string display_name { get; set; }
public string created_at { get; set; }
public int delay { get; set; }
public object game { get; set; }
public Links3 _links { get; set; }
public string updated_at { get; set; }
public object background { get; set; }
}
public class Follow
{
public string created_at { get; set; }
public Links2 _links { get; set; }
public Channel channel { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public List<Follow> follows { get; set; }
}
Now you just have to deserialize the input json string to RootObject class and fetch all the names in the input string using another utility called Json.net
string json = "JSON STRING";
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
List<string> names = root.follows.Select(follow => follow.channel.name).ToList();
foreach ( string name in names )
{
txtBox += name + "; ";
}
Ok, so i got it working now, however, if i use my username to get back json, i get a huge piece of code that you can view here: https://api.twitch.tv/kraken/users/krysvac/follows/channels
I folllow 31 people but when i use my program on it with the code
using (var w = new WebClient())
{
string json_data = w.DownloadString("https://api.twitch.tv/kraken/users/" + input + "/follows/channels");
dynamic obj = JsonConvert.DeserializeObject(json_data);
foreach (var item in obj.follows)
{
textBox1.AppendText(item.channel.name.ToString() + Environment.NewLine);
}
}
i get 25 out of my 31 people back in the textbox and i dont know why, i tried it on a person that should return more than 100 and got 6 people back.