Deserializing JSON 2-dimensional array of values
I've got a 2-dimensional array of values in JSON format:
[[57, 2], [57, 2], [58, 2], [55, 2], [60, 2], [54, 1], [59, 11]]
Each of the pairs actually contains a pair of unrelated readings, and there is one pair for each minute. So in the first min, reading 1 is 57
and reading 2 is 2
. In the second minute, the readings are the same, etc.
Now, I want to convert this into a format I can use in .Net to plot each of these readings. This could either be two parallel arrays, one for the readings of the first value with one element for each minute, and one array for all the readings of the second value. Or it could be a 2-dimensional array if this is easie开发者_如何学Cr.
I tried using DataContractJSONSerializer
without any luck:
IEnumerable<SubmissionDataRow> obj = (IEnumerable<SubmissionDataRow>)ser.ReadObject(reader, false);
where SubmissionDataRow
is just a class with a property for each of the readings but the Deserializer wouldn't know what value to put in which property!
You can do this in a couple of ways using Json.Net. If you don't mind working with a two-dimensional array of numbers, you can simply deserialize into an int[][]
:
string json = "[[57, 2], [57, 2], [58, 2], [55, 2], [60, 2], [54, 1], [59, 11]]";
int[][] values = JsonConvert.DeserializeObject<int[][]>(json);
If you would prefer to work with a strongly-typed class as you mentioned in your question, you can use a JsonConverter
to populate it.
Define your class like this:
[JsonConverter(typeof(SubmissionDataRowConverter))]
class SubmissionDataRow
{
public int Reading1 { get; set; }
public int Reading2 { get; set; }
}
And the converter like this:
class SubmissionDataRowConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(SubmissionDataRow));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JArray array = JArray.Load(reader);
return new SubmissionDataRow
{
Reading1 = array[0].Value<int>(),
Reading2 = array[1].Value<int>()
};
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Then you can deserialize like this:
List<SubmissionDataRow> rows =
JsonConvert.DeserializeObject<List<SubmissionDataRow>>(json);
Back in my .NET days I was using Jayrock and it was working like a charm.
精彩评论