Parse Json to List - json

I want to parse a json to List how can we do that. I have tried the following code but it didnt worked
Dictionary<string, object> pGateways=(Dictionary<string,object>)Json.JsonParser.FromJson(jsonString);
List<object> creditOptions = new List<object>();
creditOptions = (List<object>)pGateways;
And after getting it int list i want to loop through it
Here is my sample json
{
"MessageCode": "CS2009",
"Status": "Y",
"ErrorCode": "0",
"ErrorDescription": "Success",
"account":
{
"card":
[
{
"cardend": "asd",
"token": "aads",
"cardstart": "asdad",
"accounttype": "asda",
"cardnetwork": "as",
"issuer": "asd",
"customername": "a",
"expdate": "04/2018"
},
{
"cardend": "asda",
"token":"adssadsa",
"cardstart": "asd",
"accounttype": "asd",
"cardnetwork": "asd",
"issuer": "asda",
"customername": "asd",
"expdate": "03/2016"
}
],
"bank": []
}
}

The best option could be to use the JsonConvert in order to parse Json into a List.
Reference: JSON Parsing in Windows Phone

You can use Json.Net.
To install Json.NET use NugetGallery : Json.net Nugets Gallery
And you can use json2Csharp.com for generate c# classes from json

The JSON string you posted is not suitable for straight-forward deserialization to List. The easiest thing to do is use the online JSON 2 CSharp tool to generate classes and deserialize the json string to it. Here is an example of the generated classes:
public class Card
{
public string cardend { get; set; }
public string token { get; set; }
public string cardstart { get; set; }
public string accounttype { get; set; }
public string cardnetwork { get; set; }
public string issuer { get; set; }
public string customername { get; set; }
public string expdate { get; set; }
}
public class Account
{
public List<Card> card { get; set; }
public List<object> bank { get; set; }
}
public class RootObject
{
public string MessageCode { get; set; }
public string Status { get; set; }
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
public Account account { get; set; }
}
And here is the logic for deserialization:
var root = JsonConvert.DeserializeObject<RootObject>(jsonStr);
where the jsonStr variable holds the json string you posted.

You need to use json2csharp tool to generate classes and deserialize the JSON string to list.
Here is the Classes generated from your JSON string.
public class Card
{
public string cardend { get; set; }
public string token { get; set; }
public string cardstart { get; set; }
public string accounttype { get; set; }
public string cardnetwork { get; set; }
public string issuer { get; set; }
public string customername { get; set; }
public string expdate { get; set; }
}
public class Account
{
public List<Card> card { get; set; }
public List<object> bank { get; set; }
}
public class RootObject
{
public string MessageCode { get; set; }
public string Status { get; set; }
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
public Account account { get; set; }
}
and Deserialize your JSON object using JsonConvert,
Suppose e.result is your JSON string then
var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result);
foreach (var blog in rootObject.Card)
{
//access your data like this- `blog.cardend;` or `blog.token;`
}

Related

How to deserialize multiple objects in Xamarin Forms? [duplicate]

This question already has answers here:
How to Deserialize JSON data? C#
(5 answers)
Closed 3 years ago.
I have two different class using that I am sending json response through API to another application, in short I am getting following json response :
{
"lmob_Forms":[
{
"Fields":"Certificate Name",
"Validation":"R",
"TabIndex":"1",
"FieldType":"DropdownList",
"DateFormate":"",
"Details":null
},
],
"drop_Salutation":[
{
"id":1,
"idvalue":"Kumari"
},
{
"id":2,
"idvalue":"Mrs"
},
{
"id":3,
"idvalue":"Ms"
}
]
}
I have searched regarding the same but not able to solve this problem, Need help, Thanks In Advance :)
First of all create a model of your json object.
public class LmobForm
{
public string Fields { get; set; }
public string Validation { get; set; }
public string TabIndex { get; set; }
public string FieldType { get; set; }
public string DateFormate { get; set; }
public object Details { get; set; }
}
public class DropSalutation
{
public int id { get; set; }
public string idvalue { get; set; }
}
public class RootObject
{
public List<LmobForm> lmob_Forms { get; set; }
public List<DropSalutation> drop_Salutation { get; set; }
}
Now, simply use Newtonsoft.Json to deserialize your JSON object as:
var myObj = JsonConvert.DeserializeObject<RootObject>(jsonString);
using json2csharp
public class LmobForm
{
public string Fields { get; set; }
public string Validation { get; set; }
public string TabIndex { get; set; }
public string FieldType { get; set; }
public string DateFormate { get; set; }
public object Details { get; set; }
}
public class DropSalutation
{
public int id { get; set; }
public string idvalue { get; set; }
}
public class RootObject
{
public List<LmobForm> lmob_Forms { get; set; }
public List<DropSalutation> drop_Salutation { get; set; }
}

Get item from JSON Odata list for UWP

I have been having a hard time trying to figure this out that I've just about torn out all my hair now.
Using this section of code (Added a var result that I looking at with a stoppoint):
public async Task<string> GetHttpSPContentWithToken(string url, string token)
{
var httpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage response;
try
{
var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
//Add the token in Authorization header
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
response = await httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<SharePointListItems.Fields>(content);
return content;
}
catch (Exception ex)
{
return ex.ToString();
}
}
The content that I receive is this (updated getting rid of extra information):
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('root')/lists('FBA0AB63-8453-4BB9-AA17-142A5D72A50D')/items/$entity",
"#odata.etag": "\"60d40002-0f08-4f29-afa7-0287137b863b,1\"",
"createdDateTime": "2018-08-07T14:28:47Z",
"eTag": "\"60d40002-0f08-4f29-afa7-0287137b863b,1\"",
"id": "1",
"lastModifiedDateTime": "2018-08-07T14:28:47Z",
"webUrl": "https://XXXX.sharepoint.com/Lists/TestList/1_.000",
"createdBy": {
"user": {
"email": "XXXX#XXXX.onmicrosoft.com",
"id": "b5f81cc6-f8b7-46b7-8e10-6ce1b9689c23",
"displayName": "TK"
}
},
"lastModifiedBy": {
"user": {
"email": "XXXX#XXXX.onmicrosoft.com",
"id": "b5f81cc6-f8b7-46b7-8e10-6ce1b9689c23",
"displayName": "TK"
}
},
"parentReference": {},
"contentType": {
"id": "0x010001403BD420356E4ABE3B63E5AEC0713D"
},
"fields#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('root')/lists('FBA0AB63-8453-4BB9-AA17-142A5D72A50D')/items('1')/fields/$entity",
"fields": {
"#odata.etag": "\"60d40002-0f08-4f29-afa7-0287137b863b,1\"",
"Title": "1",
"UserName": "TK",
"UserAge": "47",
"UserTitle": "Developer"
}
}
I just want the values forUserAge, UserName, and UserTitle to put each into a textbox, but not sure how to pull them out.
I am pretty sure that I need to set up a class of some sort, but it is the #odata parts that are breaking my back.
Everything that I have tried just gives me back a null value. I see the value there, just not sure how to parse/pull it out.
I have looked at this (updated):
using Newtonsoft.Json;
using System;
public class SharePointListItems
{
public class UserCreated
{
public string email { get; set; }
public string id { get; set; }
public string displayName { get; set; }
}
public class CreatedBy
{
public UserCreated user { get; set; }
}
public class UserModified
{
public string email { get; set; }
public string id { get; set; }
public string displayName { get; set; }
}
public class LastModifiedBy
{
public UserModified user { get; set; }
}
public class ParentReference
{
}
public class ContentType
{
public string id { get; set; }
}
public class Fields
{
[JsonProperty("#odata.etag")]
public string ODataETag { get; set; }
public string Title { get; set; }
public string UserName { get; set; }
public string UserAge { get; set; }
public string UserTitle { get; set; }
}
public class RootObject
{
[JsonProperty("#odata.context")]
public string ODataContext { get; set; }
[JsonProperty("#odata.etag")]
public string ODataETag { get; set; }
public DateTime createdDateTime { get; set; }
public string eTag { get; set; }
public string id { get; set; }
public DateTime lastModifiedDateTime { get; set; }
public string webUrl { get; set; }
public CreatedBy createdBy { get; set; }
public LastModifiedBy lastModifiedBy { get; set; }
public ParentReference parentReference { get; set; }
public ContentType contentType { get; set; }
[JsonProperty("fields#odata.context")]
public string FieldsODataContext { get; set; }
public Fields fields { get; set; }
}
}
But then I run into the issue that there is two [JsonProperty("#odata.etag")].
The [JsonProperty] custom attribute is added to the C# property that actually holds that value. Instead of putting the attribute on the Title or createDateTime property, you need to put them on their own properties:
public class RootObject
{
[JsonProperty("#odata.context")]
public string ODataContext { get; set; }
[JsonProperty("#odata.etag")]
public string ODataETag { get; set; }
// No attribute needed here
public DateTime createdDateTime { get; set; }
// etc...
Also, you are trying to parse the content as a Fields class, but it is a RootObject; you need to use
JsonConvert.DeserializeObject<SharePointListItems.RootObject>(content)
To get the object.

Extracting JSON data using Newtonsoft in xamarin.android

Hello I am getting JSON data from server and i want to extract that JSON in Xamarin. How can i parse that JSON using NewTonSoft
below is the JSON responce i receive
[
{
"Id": 5,
"AlbumKey": "2REC2ZDSFK",
"ZipFillPath": "aaaa#gmail.com\\2REC2ZDSFK",
"NoOfPages": 3,
"EmailID": "aaaa#gmail.com"
}
]
This should be your Model
public class RootObject
{
public int Id { get; set; }
public string AlbumKey { get; set; }
public string ZipFillPath { get; set; }
public int NoOfPages { get; set; }
public string EmailID { get; set; }
}
Then
RootObject myObj = JsonConvert.DeserializeObject<RootObject>(json);
If your json is a List of objects, something like
List<RootObject> myListObj = JsonConvert.DeserializeObject<List<RootObject>>(json);
public class yourClass
{
public int Id { get; set; }
public string AlbumKey { get; set; }
public string ZipFillPath { get; set; }
public int NoOfPages { get; set; }
public string EmailID { get; set; }
}
Considering this as your model class you can
var responseText= JsonConvert.DeserializeObject<yourClass>(jsonResponse);
Then depending on if its a list or a not you can get the data from it
In case you are unable to find the class what you can do is check if the namespace of your current class and that class is the same.

Cannot Deserialise Json array into type string

Following id my piece of code which deserialise Json string.
response = "{\"success\":\"yes\",\"error\":\"\",\"message\":\"\",\"arguments\":[{\"id\":\"72820\",\"rowNo\":\"1\",\"userId\":\"40\",\"entityId\":\"3486\",\"value\":\"search Panel\",\"typeCategory\":\"3\"}]}";
erpAPIResponse basicResponse = JsonConvert.DeserializeObject<erpAPIResponse>(response);
Result is JSON string which is deserialised into erpAPIResponse.
My erpAPIResponse is as follows:
public string success { get; set; } // getting and setting the success
public string error { get; set; } // getting and setting the error
public string message { get; set; } // getting and setting the message
public string arguments { get; set; } // getting and setting the arguments
// public string result { get; set; }
I have verify json through JSON Lint and it is saying it is valid JSON string. So why i am getting this errorr?
As your json structure is like below:
{
"success": "yes",
"error": "",
"message": "",
"arguments": [
{
"id": "72820",
"rowNo": "1",
"userId": "40",
"entityId": "3486",
"value": "search Panel",
"typeCategory": "3"
}
]
}
Here you cannot deserialize the arguments array in a string. So you need to redefine the erpAPIResponse class like below using json2csharp utility:
public class erpAPIResponse
{
public string success { get; set; }
public string error { get; set; }
public string message { get; set; }
public List<Argument> arguments { get; set; }
}
public class Argument
{
public string id { get; set; }
public string rowNo { get; set; }
public string userId { get; set; }
public string entityId { get; set; }
public string value { get; set; }
public string typeCategory { get; set; }
}
Now you should have no problem deserializing with your original statements:
response = "{\"success\":\"yes\",\"error\":\"\",\"message\":\"\",\"arguments\":[{\"id\":\"72820\",\"rowNo\":\"1\",\"userId\":\"40\",\"entityId\":\"3486\",\"value\":\"search Panel\",\"typeCategory\":\"3\"}]}";
erpAPIResponse basicResponse = JsonConvert.DeserializeObject<erpAPIResponse>(response);

JSON to a JSON array Cannot deserialize the current JSON object

I'm using Json.Net to DeserializeObject Json data into object/collection (list)
I'm not sure what I'm doing wrong and I have tried this:
List<LanguageObject> lang = JsonConvert.DeserializeObject<List<LanguageObject>>(jsonData);
and tried this:
LanguageObject.Results lang = JsonConvert.DeserializeObject<LanguageObject.Results>(jsonData);
I'm getting this error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[LanguageObject]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'meta', line 1, position 8.
here my Json:
{"meta":
{
"status":200,
"message":[],
"resultSet":
{"id":"05"},
"pagination":
{
"count":2,
"pageNum":1,
"pageSize":2,
"totalPages":1,
"sort":"ordinal",
"order":"Asc",
"currentUri":null,
"nextUri":null
}
},
"results":
{
"id":0,
"name":
"Language",
"DName":null,
"qvalue":"language",
"language":null,
"mUsageCount":null,
"Ordinal":0,
"items":
[
{
"id":0,
"name":"English",
"DName":"English",
"qvalue":null,
"language":null,
"mUsageCount":null,
"Ordinal":0,
"items":[]
},
{
"id":0,
"name":"Spanish",
"DName":"Spanish;",
"qvalue":null,
"language":null,
"mUsageCount":null,
"Ordinal":0,"
items":[]
}
]
}}
LanguageObject.cs
Public class LanguageObject
{
public class ResultSet
{
public string id { get; set; }
}
public class Pagination
{
public int count { get; set; }
public int pageNum { get; set; }
public int pageSize { get; set; }
public int totalPages { get; set; }
public string sort { get; set; }
public string order { get; set; }
public object currentUri { get; set; }
public object nextUri { get; set; }
}
public class Meta
{
public int status { get; set; }
public List<object> message { get; set; }
public ResultSet resultSet { get; set; }
public Pagination pagination { get; set; }
}
public class Item
{
public int id { get; set; }
public string name { get; set; }
public string DName { get; set; }
public object qvalue { get; set; }
public object language { get; set; }
public object mUsageCount { get; set; }
public int Ordinal { get; set; }
public List<object> items { get; set; }
public List<object> __invalid_name__
items { get; set; }
}
public class Results
{
public int id { get; set; }
public string name { get; set; }
public object DName { get; set; }
public string qvalue { get; set; }
public object language { get; set; }
public object mUsageCount { get; set; }
public int Ordinal { get; set; }
public List<Item> items { get; set; }
}
public class RootObject
{
public Meta meta { get; set; }
public Results results { get; set; }
}
}
I don't see a LanguageObject class defined in your question. I do see a RootObject class, however. From what you have posted, you need to deserialize like this:
RootObject root = JsonConvert.DeserializeObject<RootObject>(jsonData);
Then you can get the Results from the RootObject:
Results lang = root.Results;