Querying JSON using SelectTokens? With Newtonsoft.Json.Linq in C# - c#

I'm trying to make use of Netwonsoft.JSON.Linq in C#, to change the "statusCode" values in the following JSON:
{
"disbursements":[
{
"id":"1f337641",
"contactId":"f5eb2",
"statusCode":166000005,
"amount":8,
"category":166000001
},
{
"id":"027a4762",
"contactId":"f5eb2038",
"statusCode":166000000,
"amount":4000,
"category":166000000
}
]
}
So, inside the JSON data is: "disbursements" which is JSON array. I have to change the "statusCode" of each item in the array to 166000005. I'm able to retrieve statusCode of the first one using
JObject jsonText = JObject.Parse(bodyText);
var statusCode = (int)jsonText.SelectToken("disbursements[0].statusCode");
But I need a solution with loop or LINQ that changes all the values, not just the first.

The following code sets or adds "statusCode": 166000005 to every entry in the disbursement array:
var jsonText = JObject.Parse(bodyText);
foreach (var disbursement in jsonText.SelectTokens("disbursements[*]"))
{
disbursement["statusCode"] = 166000005;
}
Notes:
The query string "disbursements[*]" contains the JSONPath wildcard operator [*]. This operator matches all array elements under the parent element "disbursement".
Json.NET supports JSONPath syntax as documented in Querying JSON with JSONPath.
SelectTokens() is used rather than SelectToken() to loop through multiple possible matches.
The JToken item setter disbursement["statusCode"] = 166000005 will replace the "statusCode" property if present and add it if not.
A simple, atomic value such as 166000005 can be set directly into a JToken hierarchy. For a complex POCO you would need to call JToken.FromObject() to serialize it to a JToken before setting it in the hierarchy, e.g.:
disbursement["statusCode"] =
JToken.FromObject( new { oldValue = disbursement["statusCode"], newValue = 166000005 } );
Sample working .Net fiddle.

I would create classes to represent the data. Here is my solution:
Create the data holder classes:
public class Disbursement
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("contactId")]
public string ContactId { get; set; }
[JsonProperty("statusCode")]
public int StatusCode { get; set; }
[JsonProperty("amount")]
public int Amount { get; set; }
[JsonProperty("category")]
public int Category { get; set; }
}
The collection:
public class Disbursements
{
[JsonProperty("disbursements")]
public List<Disbursement> Items { get; set; } = new List<Disbursement>();
}
And then the loading / modifying / saving data:
class Program
{
static void Main(string[] args)
{
var disbursements =
JsonConvert.DeserializeObject<Disbursements>(
File.ReadAllText(
"data.json",
Encoding.UTF8
)
);
foreach (var disbursement in disbursements.Items)
{
disbursement.StatusCode = 166000005;
}
string modifiedContent = JsonConvert.SerializeObject(disbursements);
File.WriteAllText(
"modifiedData.json",
modifiedContent,
Encoding.UTF8
);
}
}

Related

How do I convert json string into JsonObject and iterate on it? .NET Core 6.0 c#

As in the topic, I'm making a request to an endpoint, which in return gives me a json string. Sample json string (picked up 6 substrings, there is about thousand more):
{"probability":0.0062596053,"tagId":"sometagid","tagName":"apple","boundingBox":{"left":0.27482307,"top":0.4361664,"width":0.14311266,"height":0.37521422}},
{"probability":0.0061301645,"tagId":"sometagid","tagName":"apple","boundingBox":{"left":0.0,"top":0.44423538,"width":0.09239961,"height":0.37426883}},
{"probability":0.0059485333,"tagId":"sometagid","tagName":"carrot","boundingBox":{"left":0.037714787,"top":0.0,"width":0.15685204,"height":0.27176687}},
{"probability":0.005887271,"tagId":"sometagid","tagName":"tomato","boundingBox":{"left":0.5249929,"top":0.70379305,"width":0.44499594,"height":0.29620594}},
{"probability":0.0057223,"tagId":"sometagid","tagName":"apple","boundingBox":{"left":0.79498,"top":0.34279144,"width":0.19351125,"height":0.39170527}},
{"probability":0.0056102676,"tagId":"sometagid","tagName":"apple","boundingBox":{"left":0.030394234,"top":0.21933028,"width":0.16375154,"height":0.3037323}},
What do I need? I need this string to be splitted into these 6 (+1000) objects (preferably to an array) and I want to pick only these object that contain probability*100 > 50.
I've already made a class that contains such values as:
public class ResponseJsonNode {
public double probability { get; set; }
public string tagId { get; set; }
public string tagName { get; set; }
public BoundingBox boundingBox { get; set; }
}
And BoundingBox is another class:
public class BoundingBox {
double left { get; set; }
double top { get; set; }
double width { get; set; }
double height { get; set; }
}
Reproducible example (well not quite really because i can't post endpoint and key here):
using System.Net;
using System.Text.Json;
using ConsoleApp1;
WebRequest request = HttpWebRequest.Create("SomeUriEndpoint");
request.Method = "POST";
request.Headers.Add("some key", "some more key");
request.Headers.Add("some content type", "some more content type");
var f = File.Open(args[0], FileMode.Open);
using (var ms = new MemoryStream()) {
f.CopyTo(ms);
var fileBytes = ms.ToArray();
request.ContentLength = fileBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(fileBytes, 0, fileBytes.Length);
stream.Close();
//imageStringBase64 = Convert.ToBase64String(fileBytes);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
//JsonObject jo = (JsonObject)json;
List<ResponseJsonNode> jsonNodeList = JsonSerializer.Deserialize<List<ResponseJsonNode>>(json);
foreach(ResponseJsonNode rj in jsonNodeList) {
Console.WriteLine(rj);
}
And this gives me an error:
The JSON value could not be converted to System.Collections.Generic.List
This does not work also:
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
//JsonObject jo = (JsonObject)json;
//List<ResponseJsonNode> jsonNodeList = JsonSerializer.Deserialize<List<ResponseJsonNode>>(json);
JsonArray jsonArray = JsonNode.Parse(json).AsArray();
List<ResponseJsonNode> nodes = new List<ResponseJsonNode>();
foreach(JsonObject jo in jsonArray) {
nodes.Add(new ResponseJsonNode { probability = Convert.ToDouble(jo["probability"]), tagName = (string)jo["tagName"] });
}
var stats = new Dictionary<string, double>();
foreach (ResponseJsonNode rjn in nodes) {
if (rjn.probability * 100 > 50)
if (stats.ContainsKey(rjn.tagName)) {
stats[rjn.tagName]++;
} else {
stats[rjn.tagName] = 1;
}
}
Throws an error: System.InvalidOperationException: The node must be of type 'JsonArray'
I have tried to parse it with numerous tutorials but every one of them seems deprecated or does not work (example shown above). So what is the best possible solution for converting json string into a iterable JsonObject? (Not specificly JsonObject class that is in c# libraries but something that i could iterate on)
[Updated from clarification in this comment above.]
The JSON you're showing isn't an array. Which is why you can't deserialize it into an array. It's an object which contains an array. But in order to access that array you need to deserialize the object.
So deserialize the object. For example, using this class:
public class ResponseObject
{
public IEnumerable<ResponseJsonNode> predictions { get; set; }
}
You can deserialize your object into that class:
ResponseJsonNode jsonNode = JsonSerializer.Deserialize<ResponseObject>(json);
Basically the problem you're running into is understanding the difference between an object and an array of objects, or an object and a property on an object. You need to understand your data structure(s) in order to use that data.
If your json is literally you shown, you need to modify it a little bit, then deserialize in a standard way.
public class ResponseJsonNode {
public double Probability { get; set; }
public string TagId { get; set; }
public string TagName { get; set; }
public BoundingBox BoundingBox { get; set; }
public override string ToString() =>
$"[Node]: Probability: {Probability}; TagId: {TagId}; TagName: {TagName};\nBoundingBox: {BoundingBox}";
}
public class BoundingBox
{
public double Left { get; set; }
public double Top { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public override string ToString() => $"[L:{Left};T:{Top};Width:{Width};Height:{Height}]";
}
Deserialize then:
var json = GetJsonFromApi();
var trimmedJson = $"[{json.TrimEnd(',')}]";
var collection = JsonSerializer.Deserialize<List<ResponseJsonNode>>(trimmedJson, new JsonSerializerOptions(JsonSerializerDefaults.Web));
foreach (var item in collection)
{
Console.WriteLine($"{item}\n");
}
Btw, C# naming convention recommends name properties in a PascalCase, for deserialization from camelCase just use JsonSerializerDefaults.Web options.
and I want to pick only these object that contain probability*100 > 50.
Then simple LINQ filtration comes to the scene.

Parsing nested Json data with C#. Could not access inner element consumption

I can parse up to one nested level but I'm unable to figure out how to read the data in the consumption_history. I have been trying different ways to do it but could not get the consumption value.
I can access the miu_id and meter_number but not the array of consumption_list.
Model:
class JsonModel
{
public class Rootobject
{
public string site_id { get; set; }
public Endpoint[] endpoints { get; set; }
public Paging paging { get; set; }
}
public class Paging
{
public int page { get; set; }
public int limit { get; set; }
public int total { get; set; }
public string next { get; set; }
public object prev { get; set; }
public string self { get; set; }
}
public class Endpoint
{
public string miu_id { get; set; }
public string meter_number { get; set; }
public Consumption_History[] consumption_hist { get; set; }
}
public class Consumption_History
{
public DateTime reading_date { get; set; }
public float consumption { get; set; }
public float consumption_with_multiplier { get; set; }
}
}
Program:
static void Main(string[] args)
{
string json = File.ReadAllText(#"C:\Users\ConsoleApp3\apidataone.json");
var results = JsonConvert.DeserializeObject<JsonModel.Rootobject>(json);
JsonModel.Rootobject rootobject = JsonConvert.DeserializeObject<JsonModel.Rootobject>(json);
rootobject.endpoints = JsonConvert.DeserializeObject<JsonModel.Rootobject>(json).endpoints;
foreach (JsonModel.Consumption_History ch in rootobject.endpoints)
{
Console.WriteLine(ch.consumption);
}
}
json data:
{
"site_id":"1",
"endpoints":
[{
"miu_id":"111",
"meter_number":"88",
"consumption_history":
[{
"reading_date":"2010-02-17T00:00:00",
"consumption":1.0,
"consumption_with_multiplier":1.0
}]
}]
}
I have simplified the code a bit, instead of reading from a file I have just put the JSON content in place. This code uses Newtonsoft.Json (available via NUGET package), but the way it works is the same for other serializers.
// using Newtonsoft.Json;
void Main()
{
string json = #"{
'site_id':'1',
'endpoints':
[{
'miu_id':'111',
'meter_number':'88',
'consumption_history':
[{
'reading_date':'2010-02-17T00:00:00',
'consumption':1.0,
'consumption_with_multiplier':1.0
}]
}]
}";
dynamic j = JsonConvert.DeserializeObject<dynamic>(json);
string site_id = j["site_id"].ToString();
var endpoints = j["endpoints"];
foreach (var endpoint in endpoints)
{
string miu_id = endpoint["miu_id"];
miu_id.Dump();
// ...
var consumption_histories = endpoint["consumption_history"];
foreach(var consumption in consumption_histories)
{
string reading_date = consumption["reading_date"];
reading_date.Dump();
// ...
} // foreach
} // foreach
}
Run it in .NET fiddle
Regarding JSON: Whenever there is a [ ... ] in the JSON structure, this means there is an array ({ ... } stands for an object) - and [{ ... }] is an object inside an array; both properties and array elements are separated by comma (,); strings and property names need to be enclosed in single quotes ('...'). Value assignments are done with a colon (:). In JSON, you have either objects, strings or numeric data - these are the only types existing. If you need types, you have to cast properties into the proper types by yourself.
You can access the array either via indexer (like endpoints[i] inside a for loop), or - as I am assuming - you want to go through every element, in that case a foreach loop is easier.
Note: To use it in a for loop (like for (int i = 0; i < endpointsLength; i++) { ... }), you would have to cast endpoints and consumption_histories into an array type (e.g. via var endpoints = (object[])j["endpoints"];) and lose the simplicity dynamic provides (for example, then you would need an indexer to access a property like (endpoints[i])["miu_id"] to be able to get the value of miu_id).
The keyword dynamic simplifies things a lot in this case, this way you can keep the "JavaScript-Style" of the C# code (remember JSON comes from the JavaScript world).
If you want to introduce the classes you have declared in C#, this is also possible. For example:
foreach (Consumption_History consumption in consumption_histories)
{
string reading_date = consumption.reading_date.ToString();
reading_date.Dump();
// ...
} // foreach
You can see, that reading_date is now being accessed as C# property, and because it is of type DateTime, you need to cast it into a string first. This conversion needs to be done before the foreach loop, so you can either change the data type in your class to string to avoid that, or you can use the original code shown above and copy + convert the data into typed versions of your objects (for converting a string into DateTime, you can check this out).
If you rely on the built-in conversion NewtonSoft.JSON provides, you can simply use JsonConvert.DeserializeObject<Rootobject>(json) instead of JsonConvert.DeserializeObject<dynamic>(json). Note that implicit conversions can throw exceptions.
Also, make sure that the property names in C# and in your JSON file match exactly - if not you can decorate them in C# using attributes (see here for a description how to do that) - xdtTransform found that it is not matching for consumption_hist, and mentioned it in the comments.

Unable to map JSON response to a predefined class in C# / dynamic property name

I have a class which basically contains a property like this:
public class Msg
{
[JsonProperty(PropertyName = "XD1703301059485299")]
public Shipping shipping { get; set; }
}
the problem is in this part:
[JsonProperty(PropertyName = "XD1703301059485299")]
And the dynamic property name that I get from server...
This property name can be any name that server returns. In this particular case it's able to map the JSON to my class since the property names are same... But when server returns something like this:
XS12394124912841
The object is the null....
How can I resolve property name to be dynamic ? Can someone help me out?
P.S. This is the JSON response itself:
{"status":1,"msg":{"dynamic_name":{"order_sn":"12312313123123123","order_status":"0","shipping_info":[{"shipping_name":"","shipping_no":"","shipping_img":"","shipping_code":"","shipping_time":"","track_goods":""}]}},"errcode":0}
So I don't think this problem is as dynamic as it sounds. You can probably just convert to a dyanmic object and explicitly handle conversions.
Sample solution below. I inserted a few values to show conversion works as expected.
Add nuget package Newtonsoft.Json
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
namespace Serialize
{
public class Shipping
{
[JsonProperty(PropertyName = "shipping_name")]
public String Name { get; set; }
[JsonProperty(PropertyName = "shipping_img")]
public String Img { get; set; }
[JsonProperty(PropertyName = "shipping_code")]
public String Code { get; set; }
}
public class Order
{
public Shipping shipping { get; set; }
[JsonProperty(PropertyName = "order_sn")]
public string SerialNumber { get; set; }
[JsonProperty(PropertyName = "order_status")]
public string Status { get; set; }
}
class Program
{
static void Main(string[] args)
{
/*
{
"status":1,
"msg": {
"dynamic_name": {
"order_sn": "12312313123123123",
"order_status":"0",
"shipping_info": [{
"shipping_name":"name",
"shipping_no":"",
"shipping_img":"img",
"shipping_code":"code",
"shipping_time":"",
"track_goods":""
}]
}
},
"errcode":0
}
* */
var raw = "{ \"status\":1, \"msg\":{\"dynamic_name\":{\"order_sn\":\"12312313123123123\",\"order_status\":\"0\",\"shipping_info\":[{\"shipping_name\":\"name\",\"shipping_no\":\"\",\"shipping_img\":\"img\",\"shipping_code\":\"code\",\"shipping_time\":\"\",\"track_goods\":\"\"}]}},\"errcode\":0}";
var incomingOrder = new Order();
// properties on dynamic objects are evaluated at runtime
dynamic msgJson = JObject.Parse(raw);
// you'll want exception handling around all of this
var order = msgJson.msg.dynamic_name;
// accessing properties is easy (if they exist, as these do)
incomingOrder.SerialNumber = order.order_sn;
incomingOrder.Status = order.order_status;
// JObject cast might not be necessary. need to check for array elements, etc.
// but it's simple to serialize into a known type
incomingOrder.shipping = ((JObject)(order.shipping_info[0])).ToObject<Shipping>();
}
}
}
Alternatively, if the property name is given at runtime, you can dereference properties with the indexer getter
dynamic msgJson = JObject.Parse(raw);
JObject order = msgJson.msg["XS12394124912841"];
incomingOrder.SerialNumber = order["order_sn"].ToObject<string>();
incomingOrder.Status = order["order_status"].ToObject<string>();
incomingOrder.shipping = order["shipping_info"][0].ToObject<Shipping>();
You can implement something like this with the help of System.Web.Helpers
using (StreamReader r = new StreamReader("sample.json"))
{
string json = r.ReadToEnd();
dynamic data = Json.Decode(json);
Console.WriteLine(data["your_property"]);
}
Here sample.json contains your sample JSON response.

Unable to use JSON data with Newtonsoft.Json in WPF

I am retrieving data from office365 api. The response is in JSON format. I want to get data like Id, DisplayName etc. into variables but not getting the right way to do it. Following this link. I'm new to API and JSON. Will Appreciate pointers as well towards best learning links.Sample JSON below for listing sub folders of Inbox folder.
Response JSON data.
{"#odata.context":"https://outlook.office365.com/api/v1.0/$metadata#Me/Folders('Inbox')/ChildFolders","value":
[
{"#odata.id":"https://outlook.office365.com/api/v1.0/Users('sample.user#demosite.com')/Folders('AAMkADBjMGZiZGFlLTE4ZmEtNGRlOS1iMjllLTJmsdfsdfdDSFSDFDFDF=')",
"Id":"AAMkADBjMdfgdfgDFGDFGDFGdfGDFGDFGDFGGDzrACAAB4xqMmAAA=",
"DisplayName":"SampleFolder","ParentFolderId":"AAMkADBjMGZiZGFlLTE4ZmEtNGRlOS1sdsDFSDFSDFSDFSDFSDFDFDFrACAAAAAAEMAAA=","ChildFolderCount":0,"UnreadItemCount":8,"TotalItemCount":94},
{"#odata.id":"https://outlook.office365.com/api/v1.0/Users('sample.user#demosite.com')/Folders('AAMkADBjMGZiZGFlLTE4ZmEasdasdasdASDASDASDASDSADDASDASDAB4xqMnAAA=')",
"Id":"AAMkADBjMGZiZGFlLTE4ZmEtNGRlOS1iMjllLTJmOGZkNGRhZmIzNQAuAasdASDASDASDASEDASDASDxSEHjzrACAAB4xqMnAAA=",
"DisplayName":"AnotherSampleFolder","ParentFolderId":"AAMkADBjMGZiZGFlLTE4ZmEtNGRlOS1sdsDFSDFSDFSDFSDFSDFDFDFrACAAAAAAEMAAA=","ChildFolderCount":0,"UnreadItemCount":21,"TotalItemCount":75}
]
}
The C# code using to parse JSON and find the required data.
HttpResponseMessage response = httpClient.SendAsync(request).Result;
if (!response.IsSuccessStatusCode)
throw new WebException(response.StatusCode.ToString() + ": " + response.ReasonPhrase);
string content = response.Content.ReadAsStringAsync().Result;
JObject jResult = JObject.Parse(content);
if (jResult["odata.error"] != null)
throw new Exception((string)jResult["odata.error"]["message"]["value"]);
//Attempt one - using dynamic [NOT WORKING - getting NULL values in the variables]
dynamic results = JsonConvert.DeserializeObject<dynamic>(content);
var folderName = results.Id;
var folderId = results.Name;
//Attempt two - [Not working - Throwing exception -
//Object reference not set to an instance of an object.]
var folderID = (string)jResult["odata.context"]["odata.id"][0]["Id"];
First create a class for your json object
public class RootObject
{
[JsonProperty(PropertyName = "#odata.context")]
public string context { get; set; }
public List<Value> value { get; set; }
}
public class Value
{
[JsonProperty(PropertyName = "#odata.id")]
public string dataId { get; set; }
public string Id { get; set; }
public string DisplayName { get; set; }
public string ParentFolderId { get; set; }
public int ChildFolderCount { get; set; }
public int UnreadItemCount { get; set; }
public int TotalItemCount { get; set; }
}
Then Json Convert the Json string to your RootObject if your are using Newtonsoft Json then Deserilaze by using
RootObject shortiee = JsonConvert.DeserializeObject<RootObject>("Your Json String");
private List<string> GetDisplayNames(JObject content)
{
var obj = Json.Parse(content);
var values = obj["value"].ToList();
var displayNames = new List<string>();
foreach (var value in values)
{
displayNames .Add(system["DisplayName"].ToString());
}
return displayNames;
}
This would return the names, for example, and you could do this for each value you need to retrieve. However, this does not require you to serialize/deserialize the json object before using it. It works, but is most likely not best practice.
if (jResult["odata.error"] != null)
throw new Exception((string)jResult["odata.error"]["message"]["value"]);
//Attempt one - using dynamic [NOT WORKING - getting NULL values in the variables]
dynamic results = JsonConvert.DeserializeObject<dynamic>(content);
Side note: There is no key called "odata.error" in your JSON data. So you're effectively calling something which will return null.
One of the ways to deserialise JSON is to create model classes for the objects you want to process and deserialise into them directly, eg. JsonConvert.DeserializeObject<Folder>(content). As you are talking to an Office365 API, you find documentation and examples here on how they are defined.
Taken your folder response as an example, your model for a single Folder could look like this:
public class Folder
{
[JsonProperty(PropertyName = "#odata.id")]
public string OdataId { get; set; }
public string Id { get; set; }
public string DisplayName { get; set; }
public string ParentFolderId { get; set; }
public int ChildFolderCount { get; set; }
public int UnreadItemCount { get; set; }
public int TotalItemCount { get; set; }
}
Note1: in your example, you get a response with list of folders, so have to adjust this accordingly.
Note2: you can use JsonProperty to define a mapping between a JSON property/key and a C# property as shwon for #odata.id.
However, you can also use the Outlook Client Library which would make it mostly unnecessary to deal with JSON data directly (which seems preferable, unless you have a very specific reason to deal with JSON directly).

Parsing Json facebook c#

I am trying for many hours to parse a JsonArray, I have got by graph.facebook, so that i can extra values. The values I want to extract are message and ID.
Getting the JasonArry is no Problem and works fine:
[
{
"code":200,
"headers":[{"name":"Access-Control-Allow-Origin","value":"*"}],
"body":"{
\"id\":\"255572697884115_1\",
\"from\":{
\"name\":\"xyzk\",
\"id\":\"59788447049\"},
\"message\":\"This is the first message\",
\"created_time\":\"2011-11-04T21:32:50+0000\"}"},
{
"code":200,
"headers":[{"name":"Access-Control-Allow-Origin","value":"*"}],
"body":"{
\"id\":\"255572697884115_2\",
\"from\":{
\"name\":\"xyzk\",
\"id\":\"59788447049\"},
\"message\":\"This is the second message\",
\"created_time\":\"2012-01-03T21:05:59+0000\"}"}
]
Now I have tried several methods to get access to message, but every method ends in catch... and throws an exception.
For example:
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(json);
foreach (var item in result)
{
Console.WriteLine(item.body.message);
}
throws the exception: System.Collections.Generic.Dictionary doesnt contain definitions for body. Nevertheless you see in the screenshot below, that body contains definitions.
Becaus I am not allowed to post pictures you can find it on directupload: http://s7.directupload.net/images/120907/zh5xyy2k.png
I don't havent more ideas so i please you to help me. I need this for a project, private, not commercial.
Maybe you could give me an phrase of code, so i can continue my development.
Thank you so far
Dominic
If you use Json.Net, All you have to do is
replacing
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(json);
with
dynamic result = JsonConvert.DeserializeObject(json);
that's all.
You are not deserializing to a strongly typed object so it's normal that the applications throws an exception. In other words, the deserializer won't create an Anynymous class for you.
Your string is actually deserialized to 2 objects, each containing Dictionary<string,object> elements. So what you need to do is this:
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(s);
foreach(var item in result)
{
Console.WriteLine(item["body"]["message"]);
}
Here's a complete sample code:
void Main()
{
string json = #"[
{
""code"":200,
""headers"":[{""name"":""Access-Control-Allow-Origin"",""value"":""*""}],
""body"":{
""id"":""255572697884115_1"",
""from"":{
""name"":""xyzk"",
""id"":""59788447049""},
""message"":""This is the first message"",
""created_time"":""2011-11-04T21:32:50+0000""}},
{
""code"":200,
""headers"":[{""name"":""Access-Control-Allow-Origin"",""value"":""*""}],
""body"":{
""id"":""255572697884115_2"",
""from"":{
""name"":""xyzk"",
""id"":""59788447049""},
""message"":""This is the second message"",
""created_time"":""2012-01-03T21:05:59+0000""}}
]";
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(json);
foreach(var item in result)
{
Console.WriteLine(item["body"]["message"]);
}
}
Prints:
This is the first message
This is the second message
I am using this simple technique
var responseTextFacebook =
#"{
"id":"100000891948867",
"name":"Nishant Sharma",
"first_name":"Nishant",
"last_name":"Sharma",
"link":"https:\/\/www.facebook.com\/profile.php?id=100000891948867",
"gender":"male",
"email":"nihantanu2010\u0040gmail.com",
"timezone":5.5,
"locale":"en_US",
"verified":true,
"updated_time":"2013-06-10T07:56:39+0000"
}"
I have declared a class
public class RootObject
{
public string id { get; set; }
public string name { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string link { get; set; }
public string gender { get; set; }
public string email { get; set; }
public double timezone { get; set; }
public string locale { get; set; }
public bool verified { get; set; }
public string updated_time { get; set; }
}
Now I am deserializing
JavaScriptSerializer objJavaScriptSerializer = new JavaScriptSerializer();
RootObject parsedData = objJavaScriptSerializer.Deserialize<RootObject>(responseTextFacebook );

Categories

Resources