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);
Related
I have a json object, a string, that contains some properties and their values. Say I never know what comes in my json object, how can I loop though it and get what properties it contains? For example:
{
"aaaa": 1,
"bbbb": "qwerty",
"ccc": 21.22
}
How do I collect aaa, bbb and ccc? Once again, I don't want their values, I just want the name of the properties.
It's as simple as this:
var json = #"{ ""aaaa"": 1, ""bbbb"": ""qwerty"", ""ccc"": 21.22 }";
var jobject = Newtonsoft.Json.Linq.JObject.Parse(json);
var names = jobject.Root.Cast<JProperty>().Select(x => x.Name).ToArray();
That gives:
aaaa
bbbb
ccc
Deserialize the json to Dictionary using JsonConvert
Note: This will work if the key are always unique
var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);
Console.WriteLine($"{string.Join(",", result.Keys)}");
just in one line
IEnumerable<string> names = JObject.Parse(json).Properties().Select(x => x.Name);
this will include the names of nested objects properties
IEnumerable names = JObject.Parse(json).Descendants().OfType<JProperty>()
.Select(x => x.Name);
Im trying to use the variable OrderBy as an object key.
string OrderBy = "Entity";
output = new object[] { new { OrderBy = "asc" } };
Current output:
"orderBy":[{"OrderBy":"asc" }]
Desired output:
"orderBy":[{"Entity":"asc" }]
This:
output = new object[] { new { OrderBy = "asc" } };
Does not give this:
"orderBy":[{"OrderBy":"asc" }]
As "output". You must be serializing to JSON somehow. The best answer will depend how you are doing that - You can't dynamically set property names in C# (okay, okay, you can with reflection/emit or dynamic), something like this:
dynamic dynamicObject = new ExpandoObject();
(dynamicObject AS IDictionary<String,Object>)[OrderBy] = "asc";
// Then serialize as you are doing now
But that's sketchy and you shouldn't... You should use something like JObject, assuming you are using Newtonsoft.JSON:
JObject jsonObject = new JObject;
jsonObject[Orderby] = "asc"
var output = jsonObject.ToString();
There will be other ways with other serializers, if you say which one you are using...
Dynamic keys can be obtained by using Dictionary. And as you want to have array of them, you need to place them in List<> for example. The code become a little bit messy, but this will give you resluts you want
string OrderBy = "Entity";
var dict = new Dictionary<string, string>();
dict[OrderBy] = "asc";
List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
list.Add(dict);
var output = new { orderBy = list };
var str = JsonConvert.SerializeObject(output);
Console.WriteLine(str);
You will just have to do it this way:
var output = new object[] { new { Entity = "asc" } };
You can't replace the property name of an anonymous object with a variable, as far as I know.
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)) { ...
so I have a url encoded string which I managed to convert to json using
Request.InputStream.Position = 0;
var inputStream = new StreamReader(Request.InputStream);
var json = inputStream.ReadToEnd();
var dict = HttpUtility.ParseQueryString(json);
var json3 = new JavaScriptSerializer().Serialize(
dict.Keys.Cast<string>()
.ToDictionary(k => k, k => dict[k]));
then I eventually converted it to a dynamic object, however what I would like to do is convert some of the properties to a collection of models. Are there any methods out there that would allow me to achieve the case below without having to write my own routine:
this is what json3 looks like:
> {
"inserted[0].Property1":"dsdsdsds","inserted[0].Property2":"323","inserted[1].Property1":"dsds",
"inserted[1].Property2":"","inserted[1].Property3":"32",
"updated[0].ID":"1","updated[0].Property3":"7",
"updated[1].ID":"2","updated[1].Property3":"7","updated[1].Property4":"78",
"page":"1","size":"10","orderBy":"","groupBy":"","filter":"","aggregates":""
}
So I would like to get this and convert all the keys that starts with inserted[0] to a Model that we can call SomeClass that has Property1, Property2, ... Property4 esentially ending up with a List, same goes for all the keys that start with updated[x].
Thanks,
I'm quite new to JSON, and am currently learning about (de)serialization.
I'm retrieving a JSON string from a webpage and trying to deserialize it into an object. Problem is, the root json key is static, but the underlying keys are dynamic and I cannot anticipate them to deserialize. Here is a mini example of the string :
{
"daily": {
"1337990400000": 443447,
"1338076800000": 444693,
"1338163200000": 452282,
"1338249600000": 462189,
"1338336000000": 466626
}
}
For another JSON string in my application, I was using a JavascriptSerializer and anticipating the keys using class structure. What's the best way to go about deserializing this string into an object?
Seriously, no need to go down the dynamic route; use
var deser = new JavaScriptSerializer()
.Deserialize<Dictionary<string, Dictionary<string, int>>>(val);
var justDaily = deser["daily"];
to get a dictionary, and then you can e.g.
foreach (string key in justDaily.Keys)
Console.WriteLine(key + ": " + justDaily[key]);
to get the keys present and the corresponding values.
You can use dynamic in .NET 4 or later. For example with JSON.NET I can do:
dynamic obj = JsonConvert.Deserialize<dynamic>("{x: 'hello'}");
You can then do:
var str = obj.x;
However, unsure how it will handle numeric keys. You can of course just use JObject directly itself, for example:
var obj = JObject.Parse("{'123456': 'help'}");
var str = obj["123456"];
Whenever you have JSON with dynamic keys it can usually be deserialized into a Dictionary<string, SomeObject>. Since the inner JSON keys are dynamic (in this question) the JSON can be modelled as:
Dictionary<string, Dictionary<string, int>>
I would recommend using NewtonSoft.Json (JSON.Net) or System.Text.Json (if you're working in .NET-Core 3.0 and up).
Newtonsoft.Json
Use DeserializeObject<T> from JsonConvert:
var response = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, int>>>(json);
System.Text.Json
Use Deserialize<T> from JsonSerializer:
var response = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, int>>>(json);
This is not convenient to use, because in с# can not be defined a variable starts with a number. Add prefix to keys.
Or try this:
string json = "
{ daily:[
{ key: '1337990400000', val:443447 },
{ key: '1338076800000', val:444693 },
{ key: '1338163200000', val:452282 },
{ key: '1338249600000', val:462189 },
{ key: '1338336000000', val:466626 }]
}";
public class itemClass
{
public string key; // or int
public int val;
}
public class items
{
public itemClass[] daily;
}
items daily = (new JavascriptSerializer()).Deserialize<items>(json);
Then you can:
var itemValue = items.Where(x=>x.key=='1338163200000').Select(x=>x.val).FirstOrDefault();