Here is an example of they type JSON I get:
"Books": { "6": { "Name": "Some book" }, "7": { "Name": "Some other book" } }
in a perfect world, the api (that I cannot change) would return this inste开发者_Python百科ad:
"Books": [ { "ID": "6", "Name": "Some book" }, { "ID": "7", "Name": "Some other book" }]
Is it possible to write a JsonConverter that will push the top example into this:
[DataContract]
public class Book
{
[DataMember(Name = "ID")]
public int ID { get; set; }
[DataMember(Name = "Name")]
public string Name { get; set; }
}
Thanks
}
Unfortunately, the fact that it's just not well-formatted JSON is going to throw any library that handles JSON. The curly brackets will always be interpreted in the same way, so unless someone that understands JSON better than me has a better idea, then I think your best bet is to do some manual processing.
If the mis-formatting is consistent, then you might be able to use regular expressions to replace the mis-placed curly brackets with square brackets, and then parse it is well-formatted JSON.
Good luck!
If your input document's structure is defined fairly rigidly, you could try to just correct the document so it will parse, and then translate the document into your format.
// reference Newtonsoft.Json.dll
// using Newtonsoft.Json
// using Newtonsoft.Json.Linq
string badJson = "\"Books\": { \"6\": { \"Name\": \"Some book\" }, \"7\": { \"Name\": \"Some other book\" } }";
var source = JObject.Parse(string.Format("{{{0}}}", badJson));
var sb = new StringBuilder();
using (var writer = new JsonTextWriter(new StringWriter(sb)))
{
writer.Formatting = Newtonsoft.Json.Formatting.None;
writer.WriteStartObject();
writer.WritePropertyName("Books");
writer.WriteStartArray();
foreach (JToken child in source["Books"])
{
JProperty prop = child as JProperty;
writer.WriteStartObject();
writer.WritePropertyName("ID");
writer.WriteValue(prop.Name);
writer.WritePropertyName("Name");
writer.WriteValue((string)prop.Value["Name"]);
writer.WriteEndObject();
}
writer.WriteEndArray();
writer.WriteEndObject();
}
Console.WriteLine(sb.ToString());
This code produces the following JSON:
{"Books":[{"ID":"6","Name":"Some book"},{"ID":"7","Name":"Some other book"}]}
精彩评论