[{
"$type": "foo",
"key" : "value"
}]
I don't serialise this message, its done as part of a framework.
The array is unnecessary, I'm just interested in first type and values etc, this is invariable.
I CAN do it using the following code, but it just feels a bit nasty! I know I am being particularly stupid, I started going down the road of creating a SerializationBinder but then thought I would like to get on with my life. It can't be that hard!
var json = reader.ReadToEnd().TrimStart('[').TrimEnd(']');
var foo = JsonConvert.DeserializeObject<Foo>(json , new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All
});
As based on the comments the JSON string in the example is a valid JSON Array. Therefore the best solution would be to parse the JSON as an Array and then capture the first element. A basic example would be.
var foo = JsonConvert.DeserializeObject<Foo[]>(json)[0]
For a safer way to handle this would be to first get the array and then check if the result is valid such as.
Foo foo = fooArray.Length > 0 ? fooArray[0] : null;
And for a more generic solution can be done as a generic method.
static T DeserializeObjectFromArray<T>(string json)
where T: class
{
var arr = JsonConvert.DeserializeObject<T[]>(json);
return arr != null && arr.Length > 0 ? arr[0] : null;
}
Where in this method you can simply call
Foo foo = DeserializeObjectFromArray<Foo>(json);
This does the same as the second solution but can be reused for generic classes.
Cheers.
You can deserialize this to a list of dictionary like below
List<Dictionary<string, string>> values = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(a);
Related
I have a array of string. I want to make a JSON file from it, mapping it to a hierarchy of nested objects using the strings as property names and final value. For example, if array contains {"A", "B", "C", "D"}, then the resultant JSON file should look like
{
"A": {
"B": {
"C": "D"
}
}
}
Is there any way to do that?
You can generate a nested set of JSON objects from an array of strings using LINQ and a JSON serializer (either json.net or javascriptserializer) as follows:
var input = new[]{"A","B","C","D"};
var data = input
.Reverse()
.Aggregate((object)null, (a, s) => a == null ? (object)s : new Dictionary<string, object>{ { s, a } });
var json = JsonConvert.SerializeObject(data, Formatting.Indented);
The algorithm works by walking the incoming sequence of strings in reverse, returning the string itself for the last item, and returning a dictionary with an entry keyed by the current item and valued by the previously returned object for subsequent items. The returned dictionary or string subsequently can be serialized to produce the desired result.
Demo fiddle here.
My JSON is a very long one and i am fetching only one section "parent_crumbs" from the long JSON
...................,
"parent_crumbs":["Platforms","New platform"],
"promise_by":"2016-08-01",
....
The code I used to fetch value of "parent_crumbs" is
JObject lp_p = JObject.Parse(response_json);
string val= lp_p["parent_crumbs"].ToString();
This returns the following value
"[\r\n \"Platforms\",\"New platform\"\r\n]"
Now I have to do a comparison with the first value from the array as the string is available in a Dictionary as key value and if available return ID
Packages = new Dictionary<string, int>();
Packages.Add("Platforms", 10212);
Packages.Add("New platform", 10202);
Packages.Add("Unknown platform", 10203);
int category=
if(Packages.ContainsKey(val))
{
Packages.TryGetValue(val, out category);
}
So with current code I can't do the comparison straight away due to presence of [\r\n etc.
How to get the value as a string Array without special chars like [\r\n .
Making Model Classes for the JSON for deserialization is not preferred way for me. Since creating class is a big job for me as lot of properties are there in JSON and is dynamic of nature
We can use the below code
var input = "[\r\n \"Platforms\",\"New platform\"\r\n]";
var array =(JArray) JsonConvert.DeserializeObject(input);
bool isEqual = array[0].Value<string>() == "Platforms";
you could also convert it to array with Linq
using System.Linq;
var tmp = lp_p["parent_crumbs"].Select(x => x.ToString());
foreach (var x in tmp)
{
Console.WriteLine(x.ToString());
}
By using Select, it will help you convert it to array rather than to string
You can use DeserializeAnonymousType method for that:
var myType = new
{
parent_crumbs = new []{ "" },
promise_by = default(DateTime)
};
var result = JsonConvert.DeserializeAnonymousType(json, myType);
int category = 0;
string key = result.parent_crumbs[0];
if(Packages.ContainsKey(key))
{
Packages.TryGetValue(key, out category);
}
References: DotNetFiddle Example, DeserializeAnonymousType
I have a string in the following format:
{ "Updated" : [ { "FIRST_NAME" : "Aaa", "LAST_NAME" : "Bbb" } ] }
How can I get a dictionary out of this so I can call dict["FIRST_NAME"]?
I've tried the following, but I think they don't work because my string is a JSON array? If that's the case, how do I change it to a regular JSON string? I don't think it needs to be an array with the simple type of data that is in it... The size of the array will never be more than 1 - i.e., there will be no repeating fields.
Dictionary<string, string> dict = serializer.Deserialize<Dictionary<string, string>>(jsonString); //didn't work
JArray jArray = JArray.Parse(jsonString); //didn't work
What you are having is a complex object, which can be parsed as a Dictionary of an Array of a Dictionary!
So you can parse it like:
var dic = serializer.Deserialize<Dictionary<string, Dictionary<string, string>[]>>(jsonString)["Updated"][0];
var firstName = dic["FIRST_NAME"];
var lastName = dic["LAST_NAME"];
It might be easier to just work with a dynamic variable. See Deserialize JSON into C# dynamic object? for more details.
this is javascript code, I want to change it into C# code, same as this is, b/c again I'll change it to javascript object
data: [['2-2010',45.0],['IE', 26.8],[ 'Chrome',12.8],['Safari',8.5],['Opera',6.2],['Others', 0.7]]
actually I'm writing a wrapper which will take values in C# language and then through json serialize I'll convert the code into json.
I can't do it like this, b/c at the time of creating json it would be some thing like
C#
class dataArray
{
public string browserId;
public double percentRate;
}
JS Generated by the above class but not useable for me b/c of the variable browser and percentRate
dataArray = {browser: 'chrome', 'percentRate':30.3}
I was expecting something like this List<string,double> but it would never work :D
You need a List of object arrays to get the output that you're looking for. I used JSON.net for the example code below.
class Program
{
static void Main(string[] args)
{
List<object[]> kvp = new List<object[]>()
{
new object[] {"2-2010", 45},
new object[] {"IE", 26.8},
new object[] {"Chrome", 12.8},
new object[] {"Safari", 8.5}
};
var json = JsonConvert.SerializeObject(kvp);
Console.WriteLine(json);
//deserialize it to a List<object[]>
var json2 = "[[\"2-2010\",45.0],[\"IE\", 26.8],[\"Chrome\",12.8],[\"Safari\",8.5]]";
var kvp2 = JsonConvert.DeserializeObject<List<object[]>>(json2);
}
}
No, you'd better have an array of dictionaries, each dictionary will be equal to the object and its key and values will be his property and value
You could use anonymous types which looks a lot like the JS code, but without single quoutes around percentRate. You could also use Tuples, which is Tuple<string, float> and is basically a pair of values. Multidimensional or jagged arrays are another option.
I want to serialize dynamic object to JSON. I tried using ExpandoObject, but the result is not what I need:
public JsonResult Edit()
{
dynamic o = new ExpandoObject();
((IDictionary<string,Object>)o)["abc"] = "ABC"; //or o.abc = "ABC";
return Json(o);
}
I want JSON to look like: {"abc": "ABC"} but instead it looks like [{"Key":"abc","Value":"ABC"}]
Obviously ExpandoObject will not do, but can I inherit from DynamicObject and somehow override its methods to achieve JSON format I want?
I had this same problem and ended up fixing it by using the JSON.net (Newtonsoft.Json) serializer instead of using the JsonContent result. It then serialized my dynamic objects with normal properties versus the "key" "value" weird list.
//In my usage I had a list of dynamic objects
var output = new List<dynamic>();
//Change this
return JsonContent(new {Error = errorMessage, Results = output});
//to this
return Content(JsonConvert.SerializeObject(new {Error = errorMessage, Results = output}));
This will return what you want.
public JsonResult Edit()
{
return Json(new {abc = "ABC"});
}
This may not be useful to you, but I had a similar requirement, but used a SerializableDynamicObject
I changed the name of the dictionary to "Fields" and then this serializes with Json.Net to produce json which looks like:
{"Fields":{"Property1":"Value1", "Property2":"Value2" etc.
where Property1 and Property2 are Dynamically added properties - i.e. Dictionary Keys
It would be perfect if I could get rid of the extra "Fields" property which encapsulates the rest, but I've worked around that limitation.
You can always serialize a HashTable, its not dynamic but it supports object key value pairs.
This worked for me perfectly. You have to use Json.NET.
[HttpGet]
public string GetJson()
{
List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
List<DataEntry> properties = new List<DataEntry>();
for (int i = 0; i < 10; i++)
{
properties.Add(new DataEntry { Column = "column" + i.ToString(), Value = "value" + i.ToString() });
}
list.Add(properties.ToDictionary(x => x.Column, y => y.Value));
string test = JsonConvert.SerializeObject(list);
return test;
}