Extracting JSON data using Newtonsoft in xamarin.android - json

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.

Related

How to read json request body array object?

I am sending data in a post request as follow:
{
"HospitalId": "Hospital-0232",
"DataSliceTimestamp": "2020.08.10",
"HourQuarter": "00:01",
"Data": [
{"country":"US","state":"MS","county":"bolivar","lat":32.354668,"lng":-89.398528,"type":"ICU","measure":"1000HAB","beds":0.241539,"population":33121,"year":2014,"source":"khn","source_url":"https://khn.org/news/as-coronavirus-spreads-widely-millions-of-older-americans-live-in-counties-with-no-icu-beds/"},
{"country":"US","state":"MS","county":"bolivar","lat":32.354668,"lng":-89.398528,"type":"ICU","measure":"1000HAB","beds":0.241539,"population":33121,"year":2015,"source":"khn","source_url":"https://khn.org/news/as-coronavirus-spreads-widely-millions-of-older-americans-live-in-counties-with-no-icu-beds/"},
{"country":"US","state":"MS","county":"bolivar","lat":32.354668,"lng":-89.398528,"type":"ICU","measure":"1000HAB","beds":0.241539,"population":33121,"year":2016,"source":"khn","source_url":"https://khn.org/news/as-coronavirus-spreads-widely-millions-of-older-americans-live-in-counties-with-no-icu-beds/"},
{"country":"US","state":"MS","county":"bolivar","lat":32.354668,"lng":-89.398528,"type":"ICU","measure":"1000HAB","beds":0.241539,"population":33121,"year":2017,"source":"khn","source_url":"https://khn.org/news/as-coronavirus-spreads-widely-millions-of-older-americans-live-in-counties-with-no-icu-beds/"},
{"country":"US","state":"MS","county":"bolivar","lat":32.354668,"lng":-89.398528,"type":"ICU","measure":"1000HAB","beds":0.241539,"population":33121,"year":2018,"source":"khn","source_url":"https://khn.org/news/as-coronavirus-spreads-widely-millions-of-older-americans-live-in-counties-with-no-icu-beds/"}
]
}
And for reading the body I am doing it like this:
public class RequestBody
{
public string HospitalId { get; set; }
public string DataSliceTimestamp { get; set; }
public string HourQuarter { get; set; }
public string[] Data { get; set; }
}
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
RequestBody data = JsonConvert.DeserializeObject<RequestBody>(requestBody);
But I get error:
Newtonsoft.Json: Unexpected character encountered while parsing value: [. Path 'Data', line 5, position 13.
Something is wrong while reading array data, please guide.
You need to strongly type your JSON input to an object array not a string.
Here's an example of what the object could look like:
public class Datum
{
[JsonProperty("country")]
public string country { get; set; }
[JsonProperty("state")]
public string state { get; set; }
[JsonProperty("county")]
public string county { get; set; }
[JsonProperty("lat")]
public double lat { get; set; }
[JsonProperty("lng")]
public double lng { get; set; }
[JsonProperty("type")]
public string type { get; set; }
[JsonProperty("measure")]
public string measure { get; set; }
[JsonProperty("beds")]
public double beds { get; set; }
[JsonProperty("population")]
public int population { get; set; }
[JsonProperty("year")]
public int year { get; set; }
[JsonProperty("source")]
public string source { get; set; }
[JsonProperty("source_url")]
public string source_url { get; set; }
}
public class RequestBody
{
[JsonProperty("HospitalId")]
public string HospitalId { get; set; }
[JsonProperty("DataSliceTimestamp")]
public string DataSliceTimestamp { get; set; }
[JsonProperty("HourQuarter")]
public string HourQuarter { get; set; }
[JsonProperty("Data")]
public IList<Datum> Data { get; set; }
}
You can then deserialize it like you're already doing:
RequestBody data = JsonConvert.DeserializeObject<RequestBody>(requestBody);
I solved this by using dynamic type and by pulling out data field from the request body.
// Reading body
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
// Parse through the request body string and make it in appropriate format.
dynamic RequestBody_data = JsonConvert.DeserializeObject(requestBody);
var Data = RequestBody_data["Data"].ToString();
Through this I was able to get the data field string and then I can split it with "}," to get all the rows. Thanks

JSON.NET Error reading string. Unexpected token: StartObject. Path 'responseData',

I am trying to deserialize this link , but I keep getting this error.
Error reading string. Unexpected token: StartObject. Path 'responseData'.
From what i have googled, the problem seems to be the setup of my object I'm trying to deserialize into. Below is my class:
public class FeedSearchResult
{
[JsonProperty("responseData")]
public String ResponseData { get; set; }
[JsonProperty("query")]
public String Query { get; set; }
[JsonProperty("entries")]
public string[] Entries { get; set; }
[JsonProperty("responseDetails")]
public object ResponseDetails { get; set; }
[JsonProperty("responseStatus")]
public String ResponseStatsu { get; set; }
}
public class ResultItem
{
[JsonProperty("title")]
public String Title { get; set; }
[JsonProperty("url")]
public String Url { get; set; }
[JsonProperty("link")]
public String Link { get; set; }
}
What am I doing wrong in my class? Any help would be greatly appreciated.
Your data model only has two levels of nesting, but the JSON returned has three. If you look at the formatted JSON using https://jsonformatter.curiousconcept.com/ you will see:
{
"responseData":{
"query":"Official Google Blogs",
"entries":[
{
"url":"https://googleblog.blogspot.com/feeds/posts/default",
"title":"\u003cb\u003eOfficial Google Blog\u003c/b\u003e",
"contentSnippet":"\u003cb\u003eOfficial\u003c/b\u003e weblog, with news of new products, events and glimpses of life inside \u003cbr\u003e\n\u003cb\u003eGoogle\u003c/b\u003e.",
"link":"https://googleblog.blogspot.com/"
},
In particular your data model has responseData as a String when it needs to be a contained object. This is the specific cause of the exception.
If you upload the JSON to http://json2csharp.com/ you will get the following data model, which can be used to deserialize this JSON:
public class ResultItem
{
public string url { get; set; }
public string title { get; set; }
public string contentSnippet { get; set; }
public string link { get; set; }
}
public class ResponseData
{
public string query { get; set; }
public List<ResultItem> entries { get; set; }
}
public class RootObject
{
public ResponseData responseData { get; set; }
//Omitted since type is unclear.
//public object responseDetails { get; set; }
public int responseStatus { get; set; }
}

Parse Json to List

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;`
}

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;

Deserializing Jarray in JSON.NET

i need to deserialize this.
{"previous_cursor_str":"0","next_cursor":0,"ids":[741999686,240455509,126524150,143548100,124328422,624776268,393738125,587829914,280834485,64818350,282713007,90425850,759794,164401208,114771958,114364910,89725893],"previous_cursor":0,"next_cursor_str":"0"}
any idea?
Its a JObject really with an array of Id's inside it.
First you can create a class to represent the json like this:
public class RootObject
{
public string previous_cursor_str { get; set; }
public int next_cursor { get; set; }
public List<int> ids { get; set; }
public int previous_cursor { get; set; }
public string next_cursor_str { get; set; }
}
Then to deserialize the json into the object you do this:
var myJsonObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
Or if you just want the ids in a array:
var obj = JObject.Parse(jsonstring);
var idArray = obj["ids"].Children().Select(s=>s.value<string>());
Just tried https://jsonclassgenerator.codeplex.com/ and got the code below. Which is qhite the same as geepie's class. nice tool.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Example
{
class Result
{
[JsonProperty("previous_cursor_str")]
public string PreviousCursorStr { get; set; }
[JsonProperty("next_cursor")]
public int NextCursor { get; set; }
[JsonProperty("ids")]
public IList<int> Ids { get; set; }
[JsonProperty("previous_cursor")]
public int PreviousCursor { get; set; }
[JsonProperty("next_cursor_str")]
public string NextCursorStr { get; set; }
}
public static unsafe void Main()
{
Result result = JsonConvert.DeserializeObject<Result> (" ... your string ...");
Console.WriteLine(result);
}
}