Deserialize complex JSON at c# - c#

I get this object from API
{
"addedAt": 1573172075745,
"vid": 12590024,
"canonical-vid": 12590024,
"merged-vids": [],
"portal-id": 62515,
"is-contact": true,
"profile-token": "AO_T-mOW3t21rXoDQIhBpPulGUoTyxQKLbBxaHrS2P3MsXjF4qFJ9BIvIgkVDpeha5P3GHujF8FOP-0XFRndATAU_YogQKRBTDddOFx8s_DITNLUrnfU07QCwW61HUPygEAyDeNG6N8d",
"profile-url": "https://app.hubspot.com/contacts/62515/contact/12590024",
"properties": {
"firstname": {
"value": "Matt"
},
"lastmodifieddate": {
"value": "1573172075745"
},
"company": {
"value": "HubSpot"
},
"lastname": {
"value": "Schnitt"
}
}
}
and try to fill this model
class UserProperties
{
public string firstname { get; set; }
public DateTime lastmodifieddate { get; set; }
public string company { get; set; }
public string lastname { get; set; }
}
class UserForDeserialize
{
public int vid { get; set; }
public List<UserProperties> properties { get; set; }
}
with this code
class ApiControl
{
public void GetAllUsers()
{
using (var client = new WebClient())
{
client.Headers.Add("Content-Type:application/json");
client.Headers.Add("Accept:application/json");
var result = client.DownloadString("https://api.hubapi.com/contacts/v1/lists/recently_updated/contacts/recent?hapikey=demo&count=2");
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
dynamic dobj = jsonSerializer.Deserialize<dynamic>(result);
var obf = dobj["contacts"];
foreach (var item in obf)
{
var exampleModel = jsonSerializer.Deserialize<UserForDeserialize>(json);
}
Console.Read();
}
}
}
Id filled good but list of Properties have all null properties.
Maybe it's because of "value" field inside each property but I can't find good solution for this.
What can I try to deserialize JSON?

Your class should be like this.
public class Root
{
public long addedAt { get; set; }
public int vid { get; set; }
public int canonicalvid { get; set; }
public object[] mergedvids { get; set; }
public int portalid { get; set; }
public bool iscontact { get; set; }
public string profiletoken { get; set; }
public string profileurl { get; set; }
public Properties properties { get; set; }
}
public class Properties
{
public Firstname firstname { get; set; }
public Lastmodifieddate lastmodifieddate { get; set; }
public Company company { get; set; }
public Lastname lastname { get; set; }
}
public class Firstname
{
public string value { get; set; }
}
public class Lastmodifieddate
{
public string value { get; set; }
}
public class Company
{
public string value { get; set; }
}
public class Lastname
{
public string value { get; set; }
}
and then deserialise using this.
JavaScriptSerializer js = new JavaScriptSerializer();
Root rootObject = js.Deserialize<Root>(result );

Looks like the model generated from json is incorrect. I have used json2csharp to convert your json and the model looked like below
public class Firstname
{
public string value { get; set; }
}
public class Lastmodifieddate
{
public string value { get; set; }
}
public class Company
{
public string value { get; set; }
}
public class Lastname
{
public string value { get; set; }
}
public class Properties
{
public Firstname firstname { get; set; }
public Lastmodifieddate lastmodifieddate { get; set; }
public Company company { get; set; }
public Lastname lastname { get; set; }
}
public class UserForDeserialize
{
public int vid { get; set; }
public Properties properties { get; set; }
}
After this, I am able to read the properties
using (StreamReader r = new StreamReader(filename))
{
string json = r.ReadToEnd();
var obj = JsonConvert.DeserializeObject<UserForDeserialize>(json);
Console.WriteLine(obj.properties.firstname);
}

Change the type of your properties in 'UserProperties' for another class which contains:
public string value { get; set; }
Because you're missing that property inside your UserProperties object, I think that's the principal problem you're dealing with.

Related

How to put values in a list type field

I have 2 classes and VMs. I made a method that displays typegenres, and a list of genres that are related to them, but now I need a list of TypeGenreNamesVM. I don't understand how to pass in GenreNames a list of values Name and NameUrl. I need to make a method that displays data in a similar structure:
[
{
"name": "qwerty",
"nameEng": "qwertyEng",
"GenresNames": [
{
"name": "genre1",
"nameEng": "genreEng1"
},
{
"name": "genre2",
"nameEng": "genreEng2"
}
]
}
]
Here is I have 2 classes and VMs that I using
public class Genre
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string NameForUrl { get; set; }
public string Description { get; set; }
public int Fk_TypeGenreId { get; set; }
[ForeignKey("Fk_TypeGenreId")]
public TypeGenre TypeGenre { get; set; }
public List<Book_Genre> Book_Genre { get; set; }
}
public class TypeGenre
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string NameForUrl { get; set; }
public string Description { get; set; }
public List<Genre> Genre { get; set; }
}
public class TypeGenreTestVM
{
public string Name { get; set; }
public string NameEng { get; set; }
public List<TypeGenreNamesVM> GenreNames { get; set; }
}
public class TypeGenreNamesVM
{
public string Name { get; set; }
public string NameForUrl { get; set; }
}
public async Task<IEnumerable<TypeGenreTestVM>> GetTypesAndGenresEng()
{
var result = await _context.TypeGenre.Select(genres => new TypeGenreTestVM()
{
Name = genres.Name,
NameEng = genres.NameForUrl,
GenreNames =
}).ToListAsync();
return result;
}
Almost the same as the first Select
public async Task<IEnumerable<TypeGenreTestVM>> GetTypesAndGenresEng()
{
var result = await _context.TypeGenre.Select(genres => new TypeGenreTestVM()
{
Name = genres.Name,
NameEng = genres.NameForUrl,
GenreNames = genres.Genre.Select(g => new TypeGenreNamesVM
{
Name = g.Name,
NameEng = g.NameForUrl
})
.ToList()
}).ToListAsync();
return result;
}

Retrieve the values from json string

I have json string. I want to retrieve the contact from json string. Following json contains array of contacts. here is my json string.
{
   "contacts": {
      "contact": [
         {
            "isConnection": false,
            "id": 33554611,
            "fields": [
               {
                  "id": 33554748,
                  "type": "name",
                  "value": {
                     "givenName": "Jhon",
                     "middleName": "",
                     "familyName": "Scot",
                     "prefix": "",
                     "suffix": "",
                     "givenNameSound": "",
                     "familyNameSound": ""
                  },
                  "editedBy": "OWNER",
                  "flags": [],
                  "categories": [],
                  "updated": "2012-12-23T07:40:23Z",
                  "created": "2012-12-23T07:40:23Z",
               },
               {
                  "id": 33554749,
                  "type": "email",
                  "value": "someone#example.com",
                  "editedBy": "OWNER",
                  "flags": [],
                  "categories": [],
                  "updated": "2012-12-23T07:40:23Z",
                  "created": "2012-12-23T07:40:23Z",
               }
            ]
         }
}
}
Here I want to retrieves the values of givenName,familyName,email. How can I retrieve the values of these from json string.
Note: there are array of contact in json. I have posted only one contact from this json.
I tried something like this. But not worked.
JObject json = JObject.Parse(returnStr);
JArray fields = (JArray)json["contacts"]["contact"]["fields"][0];
JArray FValues = (JArray)json["contact"]["fields"]["value"];
I tried this
public class Field
{
public int id { get; set; }
public string type { get; set; }
public object value { get; set; }
public string editedBy { get; set; }
public List<object> flags { get; set; }
public List<object> categories { get; set; }
public string updated { get; set; }
public string created { get; set; }
public string uri { get; set; }
public bool? isConnection { get; set; }
}
public class contact
{
public bool isConnection { get; set; }
public int id { get; set; }
public List<Field> fields { get; set; }
public List<object> categories { get; set; }
public int error { get; set; }
public int restoredId { get; set; }
public string created { get; set; }
public string updated { get; set; }
public string uri { get; set; }
}
public class Contacts
{
public List<contact> contact { get; set; }
public int count { get; set; }
public int start { get; set; }
public int total { get; set; }
public string uri { get; set; }
public bool cache { get; set; }
}
public class RootObject
{
public Contacts contacts { get; set; }
}
and
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
RootObject obje = serializer1.Deserialize<RootObject>(returnStr);
But it is giving me 0 value in obje.
First make sure your Json is in valid format using jsonlint
Then generate class base on it using json2csharp
public class Field
{
public int id { get; set; }
public string type { get; set; }
public object value { get; set; }
public string editedBy { get; set; }
public List<object> flags { get; set; }
public List<object> categories { get; set; }
public string updated { get; set; }
public string created { get; set; }
}
public class Contact
{
public bool isConnection { get; set; }
public int id { get; set; }
public List<Field> fields { get; set; }
}
public class Contacts
{
public List<Contact> contact { get; set; }
}
public class RootObject
{
public Contacts contacts { get; set; }
}
Use Newtonsoft JSON to deserialize your Json into object(s) then you may simply access its properties value.
JsonConvert.DeserializeObject<RootObject>(string json);
Class for json object (generated with http://jsonutils.com/ after correcting some syntax error):
public class Field
{
public int id { get; set; }
public string type { get; set; }
public object value { get; set; }
public string editedBy { get; set; }
public IList<object> flags { get; set; }
public IList<object> categories { get; set; }
public DateTime updated { get; set; }
public DateTime created { get; set; }
}
public class Contact
{
public bool isConnection { get; set; }
public int id { get; set; }
public IList<Field> fields { get; set; }
}
public class Contacts
{
public IList<Contact> contact { get; set; }
}
public class Example
{
public Contacts contacts { get; set; }
}
Deserialization (you will probably need to add a reference to System.Web.Extensions):
System.Web.Script.Serialization.JavaScriptSerializer deSer = new System.Web.Script.Serialization.JavaScriptSerializer();
JSonPrintSettingsToXml.Input.Example deserializedJSON = deSer.Deserialize<JSonPrintSettingsToXml.Input.Example>(yourJSON);
Here is the corrected JSON
{
"contacts": {
"contact": [
{
"isConnection": false,
"id": 33554611,
"fields": [
{
"id": 33554748,
"type": "name",
"value": {
"givenName": "Jhon",
"middleName": "",
"familyName": "Scot",
"prefix": "",
"suffix": "",
"givenNameSound": "",
"familyNameSound": ""
},
"editedBy": "OWNER",
"flags": [],
"categories": [],
"updated": "2012-12-23T07:40:23Z",
"created": "2012-12-23T07:40:23Z"
},
{
"id": 33554749,
"type": "email",
"value": "someone#example.com",
"editedBy": "OWNER",
"flags": [],
"categories": [],
"updated": "2012-12-23T07:40:23Z",
"created": "2012-12-23T07:40:23Z"
}
]
}
]
}
}
You need to go with the following structure:
public class Contact
{
public bool isConnection { get; set; }
public int id { get; set; }
public List<Field> fields { get; set; }
}
public class Field
{
public int id { get; set; }
public string type { get; set; }
public object value { get; set; }
public string editedBy { get; set; }
public string[] flags { get; set; }
public string[] categories { get; set; }
public DateTime updated { get; set; }
public DateTime created { get; set; }
}
public class Name
{
public string givenName { get; set; }
public string middleName { get; set; }
public string familyName { get; set; }
public string prefix { get; set; }
public string suffix { get; set; }
public string givenNameSound { get; set; }
public string familyNameSound { get; set; }
}
And then deserialize it and use LINQ to manipulate fields.
If you want to stick to JObject and not create classes, look at the example provided at http://weblog.west-wind.com/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing
You'll have to enumerate over this
dynamic contacts = (JArray)json["contacts"]
foreach(dynamic contact in contacts.contact) {
// look at the fields...
}
PS. Give it a go, don't have VS on me so cant quite verify the exact syntax
Firstly, I think you'll find that your JSON is not well-formed. You don't need the extra commas after the two "created" dates and there is a right-square bracket missing before the second last curly brace. I recommend you always validate your JSON using this awesome site: http://jsonformatter.curiousconcept.com
Secondly, you are not referencing the array elements correctly. Although I agree with #grundy that you should be creating class definitions for managing JSON and using LINQ, there is absolutely nothing wrong with the Newtonsoft library. You can still persist with your method.
Try this:-
var json = JObject.Parse(returnStr);
var fields = (JArray)json["contacts"]["contact"][0]["fields"];
var givenName = fields[0]["value"]["givenName"];
var familyName = fields[0]["value"]["familyName"];
var email = fields[1]["value"];

Deserializing Onedrive REST data

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.

Get text in string between text in said string

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.

How to deserialize JSON to .NET object using JSON.NET?

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

Categories

Resources