I have the following JSOn I need to parse:
{"items":[{"dict":"es","words":[{"word":"car","id":"3487"},{"word":"dog","id":"443"},{"word":"plane","id":"1171"}]},{"dict":"fr","words":[{"word":"house","id":"134"}]}]}
Using JavaScriptSerializer, how could I iterate first through each dict and then retrieve the id of each word?
make anonymouse type, acording your json, for example:
var result = new[] {new {action = "", value = false}}; // put your item structure here
var list = JsonConvert.DeserializeObject(myJson, result.GetType());
then you might want to itterate through. For example:
foreach (dynamic val in ((dynamic) list)) { ...
Related
I have a json string like this:
{
"ipaddress": "xxx",
"hostname": "comcast.xxx",
"popup": {
"position": "1256",
"pagename": "home"
}
}
In my Windows Form code I've been using JavaScriptSerializer for phare those line to dictionary.
var obj = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
It is working fine at the moment, but I don't know how to get value inside popup? Because it's another dictionary.
[7] = {[popup, System.Collections.Generic.Dictionary`2[System.String,System.Object]]}
The fastest (yet unsafe) way of doing it is like this is via the indexer:
First extract the first dictionary and cast, since the first dictionary will yield an object of type object:
var popup = (Dictionary<string, object>)obj["popup"];
Then, you extract the values based on keys:
var position = popup["position"];
var pagename = popup["pagename"];
If you're not sure both keys will exist in the result, you can use Dictionary.TryGetValue if they exist:
obj position;
if (!popup.TryGetValue("position", out position))
{
// Key isn't in the dictionary.
}
Use JSON .Net, then simply:
JObject dynJson = JObject.Parse(jsonString);
followed by:
string data = dynJson["popup"]["position"];
JObject.Parse
Platform: C#
IDE: Visual Studio 2010
I am trying to read all the values from json object and put it in the list of string , for which I am doing Json deserialize but it throws me error...
Here is what I have tried
List<string> lstPName = new List<string>();
JavaScriptSerializer strJsonSer = new JavaScriptSerializer();
localhost.Pstats objStats = new localhost.Pstats();
var strJson = objStats.GetAutoCompleteData(txtSearchBox.Text.Trim());
lstPName = strJsonSer.DeserializeObject<string>(strJson);
Here is what the Json object holds
[{"PlayerName":"WA Mota"},{"PlayerName":"Atif Ahmed"}]
So, I need the player name value to be added in the list...
Simple and straightforward solution:
var strJson = "[{\"PlayerName\":\"WA Mota\"},{\"PlayerName\":\"Atif Ahmed\"}]";
var strJsonSer = new JavaScriptSerializer();
var list = new List<string>();
var result = strJsonSer.DeserializeObject(strJson) as object[];
if (result != null)
{
foreach (Dictionary<string, object> x in result)
{
list.Add(x["PlayerName"].ToString());
}
}
Or, if you are preferring LINQ - you can use instead of foreach loop something like:
list = result
.Cast<Dictionary<string, object>>()
.Select(x => x["PlayerName"].ToString())
.ToList();
Key idea: DeserializeObject used for parsing JSON data like yours gives you array of Dictionary<string, object> where key is JSON property name and value is JSON property value. Size of array equals to objects count in your JSON data.
I have the following json data, I need to read the data from it and them perform some comparisons.
{"expiration": "2013-04-01T00:00:00Z",
"conditions": [
{"bucket": "the-s3-bucket-in-question"},
["starts-with", "$key", "donny/uploads/"],
{"acl": "private"},
["eq", "$Content-Type", "text/plain"],
["starts-with", "x-amz-meta-yourelement", ""],
["content-length-range", 0, 1048576]
]
}
By using the following code I have found the first element
var policy = Encoding.UTF8.GetString(policyByteArray);
JObject obj = JObject.Parse(policy);
string policyexpiration = obj.First.First.Path;
I have used JToken for finding all the conditions but I am getting only one element in that array. Can you please help me to get all the elements present in the conditions.
Following is the way I have used JToken
JToken entireJson = JToken.Parse(policy);
var items = entireJson["conditions"].Value<JArray>()[0];
XmlDocument xdoc = (XmlDocument)JsonConvert.DeserializeXmlNode(items.ToString(), "root");
XmlNode xmlarray = xdoc.GetElementsByTagName("root")[0];
foreach (XmlNode xmlelement in xmlarray)
{
}
I'm not sure why you need the XML tools at all. Iterating the "conditions" in your json structure is simple with Json.NET and you're already very close.
var items = entireJson["conditions"].Value<JArray>();
foreach (JToken condition in items)
{
//do work on one condition here
}
Note that this json structure is a little odd. A single condition can either be an array such as ["starts-with", "$key", "donny/uploads/"] OR an object such as {"bucket": "the-s3-bucket-in-question"}.
Depending what you want to do with the conditions, you may need to distinguish between the two. You can use C#'s is operator with the Json.NET types, like this:
var items = entireJson["conditions"].Value<JArray>();
foreach (JToken condition in items)
{
if (condition is JArray)
{
//do something with the array
}
else if (condition is JObject)
{
//do something with the object
}
}
You are you only getting one element because you are selecting the value at index 0 of the JArray
var items = entireJson["conditions"].Value<JArray>()[0];
Instead of using the Value method, use Values which returns an IEnumerable
var items = entireJson["conditions"].Values<JObject>();
As far as I know DeserializeXmlNode() only accept string that represent JSON object. That's why it worked when you passed only the first value of conditions property :
var items = entireJson["conditions"].Value<JArray>()[0];
XmlDocument xdoc = JsonConvert.DeserializeXmlNode(items.ToString(), "root");
But throwing exception if you pass the entire value or the second value of conditions because both represent JSON array instead of JSON object :
//pass entire value
var items = entireJson["conditions"].Value<JArray>();
//or pass the second value : ["starts-with", "$key", "donny/uploads/"]
var items = entireJson["conditions"].Value<JArray>()[1];
XmlDocument xdoc = JsonConvert.DeserializeXmlNode(items.ToString(), "root");
It isn't clear what kind of XML format you want to create from given JSON string. But just to make it work, you can try to create another JSON object having one property named conditions with value copied from the initial JSON :
var items = entireJson["conditions"].Value<JArray>();
var newObject = string.Format("{{conditions : {0}}}", items.ToString());
XmlDocument xdoc = (XmlDocument)JsonConvert.DeserializeXmlNode(newObject, "root");
I'm try to parse some JSON like this:
{
"results": [
"MLU413843206",
"MLU413841098",
"MLU413806325",
"MLU413850890",
"MLU413792303",
"MLU413843455",
"MLU413909270",
"MLU413921617",
"MLU413921983",
"MLU413924015",
"MLU413924085"
]
}
All is fine until I try to obtain the values themselves, for example:
// The JSON is shown above
var jsonResp = JObject.Parse(json);
var items = jsonResp["results"].Children();
I don't know how to obtain the values, each converted to string. Does somebody know how to do this?
You're halfway there. You can use the Select() method in the System.Linq namespace to project the IEnumerable<JToken> returned from the Children() method into an IEnumerable<string>. From there you can loop over the values using foreach, or put the values into a List<string> using ToList() (or both).
string json = #"
{
""results"": [
""MLU413843206"",
""MLU413841098"",
""MLU413806325"",
""MLU413850890"",
""MLU413792303"",
""MLU413843455"",
""MLU413909270"",
""MLU413921617"",
""MLU413921983"",
""MLU413924015"",
""MLU413924085""
]
}";
JObject jsonResp = JObject.Parse(json);
List<string> items = jsonResp["results"].Children()
.Select(t => t.ToString())
.ToList();
foreach (string item in items)
{
Console.WriteLine(item);
}
Fiddle: https://dotnetfiddle.net/Jcy8Ao
In my controller, I get a string that is JSON:
String json_string = this.Request.Content.ReadAsStringAsync().Result;
That looks something like so:
{
"21": {"Id":21,"DisplayOrder":3, ... snip ... },
"333":{"Id":333,"DisplayOrder":2, ... snip ... },
"591":{"Id":591,"DisplayOrder":1, ... snip ... }
}
I don't have a say in the structure of this JSON so can't format it into something without keys. They keys aren't necessary since the ID is within the Value of that Dictionary.
In any case, how do I convert json_string in such a way that allows me to pull out the only two items I want when I iterate over the 'rows' in that structure... Id, DisplayOrder?
Like so:
int Id = row_item.Id;
int DisplayOrder = row_item.DisplayOrder;
Thanks!
Eric
string json = #"{
""21"": {""Id"":21,""DisplayOrder"":3},
""333"":{""Id"":333,""DisplayOrder"":2},
""591"":{""Id"":591,""DisplayOrder"":1}}";
var list = new JavaScriptSerializer()
.Deserialize<Dictionary<string, Dictionary<string, object>>>(json)
.Values
.ToList();
Console.WriteLine(list[0]["Id"]); // <--21
You can also do the same thing with Json.Net
var jObj = JsonConvert
.DeserializeObject<Dictionary<string, Dictionary<string, object>>>(json)
.Values
.ToList();
Console.WriteLine(jObj[0]["Id"]);
dynamic can be utilized too
var jObj = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json)
.Values
.ToList();
Console.WriteLine(jObj[0].DisplayOrder);