How do I parse a JSON object in C# when I don’t know the key in advance?

It’s doable; this works but it’s not elegant. I’m sure there’s a better way. var o = JObject.Parse(yourJsonString); foreach (JToken child in o.Children()) { foreach (JToken grandChild in child) { foreach (JToken grandGrandChild in grandChild) { var property = grandGrandChild as JProperty; if (property != null) { Console.WriteLine(property.Name + “:” + property.Value); } } } … Read more

Json.net serialization of custom collection implementing IEnumerable

As of Json.NET 6.0 Release 3 and later (I tested on 8.0.3), this works automatically as long as the custom class implementing IEnumerable<MyType> has a constructor that takes an IEnumerable<MyType> input argument. From the release notes: To all future creators of immutable .NET collections: If your collection of T has a constructor that takes IEnumerable … Read more

Jackson deserialize based on type

Annotations-only approach Alternatively to the custom deserializer approach, you can have the following for an annotations-only solution (similar to the one described in Spunc’s answer, but using type as an external property): public abstract class AbstractData { private Owner owner; private Metadata metadata; // Getters and setters } public static final class FooData extends AbstractData … Read more

CORS enabled but response for preflight has invalid HTTP status code 404 when POSTing JSON

Thanks but getting 405 error,after the above config changes. Finally it works after adding below code in web api Global.asax file protected void Application_BeginRequest(Object sender, EventArgs e) { //HttpContext.Current.Response.AddHeader(“Access-Control-Allow-Origin”, “*”); if (HttpContext.Current.Request.HttpMethod == “OPTIONS”) { HttpContext.Current.Response.AddHeader(“Cache-Control”, “no-cache”); HttpContext.Current.Response.AddHeader(“Access-Control-Allow-Methods”, “GET, POST”); HttpContext.Current.Response.AddHeader(“Access-Control-Allow-Headers”, “Content-Type, Accept”); HttpContext.Current.Response.AddHeader(“Access-Control-Max-Age”, “1728000”); HttpContext.Current.Response.End(); } }

Extract data from Json string

img_url is not a property of root object – it’s a property of data object: var obj = JObject.Parse(json); var url = (string)obj[“data”][“img_url”]; // http://s1.uploads.im/D9Y3z.png Another option: var url = (string)obj.SelectToken(“data.img_url”);

JavaScript – Escape double quotes

It should be: var str=”[{“Company”: “XYZ”,”Description”: “\\”TEST\\””}]”; First, I changed the outer quotes to single quotes, so they won’t conflict with the inner quotes. Then I put backslash before the innermost quotes around TEST, to escape them. And I escaped the backslash so that it will be treated literally. You can get the same result … Read more