How to parse the Json data in WP8? - json

I'm newbie to windows phone 8 development. I am working on application in which I need parse the Json. please help me with this json data
{
"School": [
{
"info": {
"name": "Dary",
"description": "Student",
"startAt": "",
"endAt": "",
"status": "approved",
"type": 7
},
"gui": {
"size": 60,
"sizeMB": "1.7 M"
}
},
{
"info": {
"name": "Henry",
"description": "Student",
"startAt": "",
"endAt": "",
"status": "approved",
"type": 7
},
"gui": {
"size": 60,
"sizeMB": "1.7 M"
}
}
]
}
this is class
public class Info
{
public string name { get; set; }
public string description { get; set; }
public string startAt { get; set; }
public string endAt { get; set; }
public string status { get; set; }
public int type { get; set; }
}
public class Gui
{
public int size { get; set; }
public string sizeMB { get; set; }
}
public class School
{
public Info info { get; set; }
public Gui gui { get; set; }
}
public class RootObject
{
public List<School> School { get; set; }
}
Thanks in advance.

As Peter Torr suggests, JSON.NET is a great option. There is a DataContractJsonSerializer for serialization in the .net framework, but its not very robust. You can easily add JSON.NET to your project with Nuget. Place your json in a string variable
string json = "<<your json string>>"
or read from a file
string json = File.ReadAllText("<<path to file>>");
Then, the following code will deserialize your text.
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
You can lose the root object (it looks like it came from a javascript to C# converter) if you keep only the json array (the text between the brackets [] ), and then you can deserialize just the array.
List<School> school = JsonConvert.DeserializeObject<List<School>>(json);

Related

How to prepare json or json array for api in .net core using httpclient

I want to prepare a json like below using c#. I want to use it for post api call. How can I do it?
{
"inputs": [
{
"person": {
"name": "xyz",
"country": "india",
"phone": "9999999999",
}
},
{
"person": {
"name": "abc",
"country": "india",
"phone": "8888888888",
}
}
]
}
If you want to bind json array from appsetting.json to class, you can use following code:
create three models
public class person
{
public string name { get; set; }
public string country { get; set; }
public string phone { get; set; }
}
public class inputs
{
public person person { get; set; }
}
public class conf
{
public inputs[] inputs { get; set; }
}
Inject them into container in program.cs(.Net 6)
builder.Services.Configure<conf>(builder.Configuration);
Then in your controller, Using Dependency Injection in the Constructor to Get the Value
public class HomeController : Controller
{
private readonly IOptions<conf> _option;
public HomeController(ILogger<HomeController> logger, IConfiguration configuration,IOptions<conf> option)
{
_option = option;
}
Finally, You can use model's properties to get the value from appsetting.json

Xamarin Refit - Newtonsoft.Json.JsonSerializationException

I have some problems with JSON Serialization.
When I try to deserialize my JSON Object, it returns me this error :
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Project.Models.BookModel' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
My problem here is that I have to deserialize my object in two different ways : In a JSON array(e.g.[1,2,3]) to extract "_id", "user" and "name", and then in a JSON array(e.g.["name":"value"]) to extract "books". And I don't know how to do it. Or more precisely, I don't know if it's posible with Refit.
Here is my JSON :
[
{
"_id": "5c014a1e43b6804ed7b642b2",
"__v": 0,
"user": "5c014a1d43b6804ed7b642b1",
"name": "Favoris",
"books": [
{
"_id": "5a8f12e16a16fa06d1f5b0cb",
"title": "Harry Potter et la Chambre des Secrets",
"author": {
"_id": "5a8f12e16a16fa06d1f5b0bd",
"name": "J K Rowling",
"__v": 0
},
"literaryGenre": "Juvenile Fiction",
"isbn": 9781781101049,
"externalImage": "...",
"__v": 0,
"content": {
"brief": "test1"
}
},
{
"_id": "5a8f12e16a16fa06d1f5b0d0",
"title": "Harry Potter et la Coupe de Feu",
"author": {
"_id": "5a8f12e16a16fa06d1f5b0bd",
"name": "J K Rowling",
"__v": 0
},
"literaryGenre": "Juvenile Fiction",
"isbn": 9781781101063,
"externalImage": "...",
"__v": 0,
"content": {
"brief": "test2"
}
}
]
}
]
Here is my code :
public async void ViewLibrary()
{
IProjectApi response = ProjectRepository.Instance.ProjectApi;
List<LibraryModel> library = await response.GetLibrary("5c014a1d43b6804ed7b642b1");
this.LibraryItems = library;
}
And my object LibraryModel :
public class LibraryModel
{
public string _id { get; set; }
public string user { get; set; }
public string name { get; set; }
public BookModel books { get; set; }
}
And my method GetLibrary :
[Get("/api/library/user/{UserId}")]
Task<List<LibraryModel>> GetLibrary(string UserId);
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'Project.Models.BookModel' because the type requires a JSON object
(e.g. {"name":"value"})
In json result your BookModel returning multiple records, so it should be defined as List<BookModel>.
In LibraryModel try using public List<BookModel> books { get; set; }.
Implement these classes anywhere in your code and try to deserialize your json with these classes.
public class Author
{
public string _id { get; set; }
public string name { get; set; }
public int __v { get; set; }
}
public class Content
{
public string brief { get; set; }
}
public class Book
{
public string _id { get; set; }
public string title { get; set; }
public Author author { get; set; }
public string literaryGenre { get; set; }
public object isbn { get; set; }
public string externalImage { get; set; }
public int __v { get; set; }
public Content content { get; set; }
}
public class RootObject
{
public string _id { get; set; }
public int __v { get; set; }
public string user { get; set; }
public string name { get; set; }
public List<Book> books { get; set; }
}

Newtonsoft json and graph api

i use Newtonsoft json to Deserialize facebook graph api response.
for example when i parse user posts that the response is like:
data": [
{
"story": "",
"created_time": "",
"id": ""
}]
i have created a class like:
public class FacebookPost
{
public string created_time { get; set; }
public string id { get; set; }
public string story { get; set; }
}
and the Newtonsoft appends the values directly in the class and i can use them.
my problem is when i am trying to parse comments when the api response is like:
"data": [
{
"created_time": "",
"from": {
"name": "",
"id": ""
},
"message": "",
"id": ""
}]
there for example the name and id is inside the from section,
how do i have to structure the classes in order to can take values for from.name and from.id?
thank you very much
---------------------------- new add ------
i use the following classes :
public class FacebookCommentsResults
{
public PostComments[] data { get; set; }
public FacebookPagingInfo Paging { get; set; }
}
public class PostComments
{
public string created_time { get; set; }
public From from { get; set; }
}
public class From
{
public string name { get; set; }
public string id { get; set; }
}
the line var created_time = comment.created_time; WORKS FINE!
the next line var name = comment.name; GIVES ERROR --> Reactions.PostComments' does not contain a definition for 'name' and no extension method 'name' accepting a first argument of type 'Reactions.PostComments' could be found (are you missing a using directive or an assembly reference?)
when the response is
"data": [
{
"created_time": "",
"from": {
"name": "",
"id": ""
},
"message": "",
"id": ""
}]
Now the json schema is changed, so we have to change our Classes. Reason is from is an another object in our main json, so we need the below classes to access from.id and from.name
public class From
{
public string name { get; set; }
public string id { get; set; }
}
public class FacebookPost
{
public string created_time { get; set; }
public From from { get; set; }
public string message { get; set; }
public string id { get; set; }
}
Edit
the line var created_time = comment.created_time; WORKS FINE! the next
line var name = comment.name; GIVES ERROR --> Reactions.PostComments'
does not contain a definition for 'name' and no extension method
'name' accepting a first argument of type 'Reactions.PostComments'
could be found (are you missing a using directive or an assembly
reference?)
from is an object and in that object name is an attribute, so you cannot access it by giving comment.name. First you need to take the from object from comment and then you can retrieve the name attribute.

How to create Models in ASP.Net for multi level Json format?

Problem Specification: Build a web api in asp.net to post multi level json formatted data.
Json Format:
{
"InfoList:"[
{
"Name": " Sample String 1",
"URL": " Sample String2",
"Info":[
{
"ZIP": " Sample String3 "
"status": "Sample String4"
}
]
}
]
}
I tried to solve this problem. My models are given bellow:
My Models:
public class Information : InfoList
{
public InfoList InfoList { get; set; }
}
public class InfoList
{
public string Name { get; set; }
public string URL { get; set; }
public Info info { get; set; }
}
public class Info
{
public string ZIP{ get; set; }
public string status { get; set; }
}
Those models Generates this kind of Json Format:
{
"InfoList": {
"Name": "sample string 1",
"URL": "sample string 2",
"Info": {
"ZIP": "sample string 1",
"status": "sample string 2"
}
},
"Name": "sample string 1",
"URL": "sample string 2",
"Info": {
"ZIP": "sample string 1",
"status": "sample string 2"
}
}
I need those parentheses exactly like the problem specification.What to do? I am working with ASP.Net Web API controller.
You're inheriting Information from InfoList so naturally it will get the fields Name, URL etc. Remove the inheritance and change the InfoList and Info members into arrays or lists and you get what you want.
public class Information
{
public InfoList[] InfoList { get; set; }
}
public class InfoList
{
public string Name { get; set; }
public string URL { get; set; }
public Info[] info { get; set; }
}
public class Info
{
public string ZIP{ get; set; }
public string status { get; set; }
}
You just copy your JSON then create C# Class file. Then click Edit -> Paste Special -> Paste JSON as Classes. Thats it...
You need Visual Studio for this.
For more information please see below link
How to show the "paste Json class" in visual studio 2012 when clicking on Paste Special?
Valid JSON
{
"InfoList": {
"Name": " Sample String 1",
"URL": " Sample String2",
"Info": [
{
"ZIP": " Sample String3 ",
"status": "Sample String4"
}
]
}
}
So your class must be like this.
public class Rootobject
{
public Infolist InfoList { get; set; }
}
public class Infolist
{
public string Name { get; set; }
public string URL { get; set; }
public Info[] Info { get; set; }
}
public class Info
{
public string ZIP { get; set; }
public string status { get; set; }
}
You can use http://json2csharp.com/ online tool to create c# class from json data string. Just copy your json and get classes.

Trouble deserializing Json from REST service

I'm having the hardest time deserializing a json string.
I was using the RestSharp api which worked great if I specified the RootElement on the request. I then moved to Hammock for the OAuth functionality, but the deserialization isn't working so easily.
I've tried using DataContractJsonSerializer
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List));
var member = (List)ser.ReadObject(response.ContentStream);
but this gives me an InvalidCastException.
I tried JsonConvert
var members = JsonConvert.DeserializeObject<List<Member>>(response.Content);
but I get the exception: Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[Member]'.
RestSharp took care of this easily when calling ExecuteAsync. Client.ExecuteAsync<List<Member>>(request, (response) =>
I'm at my wits end. Maybe I need a Hammock equivalent to RestSharp's RootElement property?? Is it just that my Json is difficult to convert?
Here is my Member object
public partial class Member
{
public string State { get; set; }
public string Joined { get; set; }
public string lat { get; set; }
public string Zip { get; set; }
public string Bio { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Id { get; set; }
public string Link { get; set; }
public string Country { get; set; }
public string Visited { get; set; }
public string Photo_url { get; set; }
public string lon { get; set; }
}
here is the Json:
{
"results": [
{
"zip": "11111",
"lon": "-122.22000122070312",
"photo_url": "http: //photos1.aaaaa.com/photos/member/1/6/c/e/member_4469838.jpeg",
"link": "http: //www.aaaa.com/members/7804365",
"state": "AA",
"lang": "en_US",
"city": "MyCity",
"country": "us",
"id": "7804365",
"visited": "Sat Feb 19 02: 36: 40 EST 2011",
"topics": [
{
"id": 3340,
"urlkey": "pickupsoccer",
"name": "Pick-up Soccer"
},
{
"id": 468,
"urlkey": "dads",
"name": "Dads"
},
{
"id": 20557,
"urlkey": "coed-soccer",
"name": "Coed Soccer"
},
{
"id": 148421,
"urlkey": "windowsphone",
"name": "Windows Phone"
}
],
"joined": "Thu Aug 07 15: 32: 06 EDT 2008",
"bio": "",
"name": "aaa bbbb",
"other_services": {
"linkedin": {
"identifier": "http: //www.bbb.com/in/zzzzz"
}
},
"lat": "47.790000915527344"
}
],
"meta": {
"lon": "",
"count": 1,
"link": "https: //api.aaaaa.com/members",
"next": "",
"total_count": 1,
"url": "https: //api.aaaaa.com/members?relation=self&order=name&offset=0&format=json&page=800",
"id": "",
"title": "Members",
"updated": "Fri Sep 10 13: 08: 07 EDT 2010",
"description": "API method",
"method": "Members",
"lat": ""
}
}
UPDATE
Adding a wrapper object for my Member class that encapsulates the entire json result fixed this.
public partial class Members
{
public List<Member> results { get; set; }
public object meta { get; set; }
}
Then I can can deserialize using the following:
var members = JsonConvert.DeserializeObject<Members>(jsonstring);
There are about three problem areas in your JSON data:
The way it is presented here, it contains a lot of backslashes and double quotes at the beginnging and end that don't work in JSON. It's difficult to tell from your question whether this is an artifact of copying it from the VisualStudio debugger or is really a problem in the data.
The transmitted data is not a list of Member instance but rather an object containing both a list of member instances and some additional meta information. So you need to introduce an additional class with a the two members results and meta.
Your class Member uses properties starting with an uppercase letter while the JSON data uses all lowercase letters. You can either change the property names or uses data DataMember annoation:
So the solution could be:
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(JsonResponse));
JsonResponse jsonResponse = (JsonResponse)ser.ReadObject(response.ContentStream);
with the following class definitions:
[DataContract]
public partial class Member
{
[DataMember(Name = "state")]
public string State { get; set; }
[DataMember(Name = "joined")]
public string Joined { get; set; }
[DataMember(Name = "lat")]
public string Lat { get; set; }
[DataMember(Name = "zip")]
public string Zip { get; set; }
[DataMember(Name = "bio")]
public string Bio { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "state")]
public string City { get; set; }
[DataMember(Name = "city")]
public string Id { get; set; }
[DataMember(Name = "link")]
public string Link { get; set; }
[DataMember(Name = "country")]
public string Country { get; set; }
[DataMember(Name = "visited")]
public string Visited { get; set; }
[DataMember(Name = "photo_url")]
public string PhotoUrl { get; set; }
[DataMember(Name = "lon")]
public string Lon { get; set; }
}
[DataContract]
public class Meta
{
[DataMember(Name = "lon")]
public string Lon { get; set; }
[DataMember(Name = "count")]
public int Count { get; set; }
[DataMember(Name = "link")]
public string Link { get; set; }
[DataMember(Name = "next")]
public string Next { get; set; }
[DataMember(Name = "total_count")]
public int TotalCount { get; set; }
}
[DataContract]
public class JsonResponse
{
[DataMember(Name = "results")]
public List<Member> Results { get; set; }
[DataMember(Name = "meta")]
public Meta Meta { get; set; }
}
In our project we r using Hammok for this, you can try to modify your class like this:
[DataContract]
public partial class Member
{
[DataMember(Name="zip")]
public string Zip { get; set; }
[DataMember(Name="photo_url")]
public string Photo_url { get; set; }
//Etc.
}
try using Json.net.
i found DataContractJsonSerializer too fetureless.
json.net provides great functionality.
it can be found at this link
http://json.codeplex.com/
it contains the .dll files and documentatio as well.
for web Documentation
http://james.newtonking.com/projects/json/help/