我正在与返回包含true,false或字符串数组数组的JSON的API进行通信。我希望反序列化这个JSON,并在名为Success of data type bool的类字段中存储boolean值(如果有),并在名为Result of a custom data of type的字段中存储该数组(如果有)。
实现这一目标最好的是什么?
一些JSON:
[
{"status":"ok","result":true},
{
"status":"ok",
"result":
[
{"name":"John Doe","UserIdentifier":"abc","MaxAccounts":"2"}
]
}
]
我的结果课程:
class Result
{
string Name,
string UserIdentifier,
string MaxAccounts
}
与Api通信的类:
class Api
{
public string Status { get; set; }
public Result[] Result { get; set; }
public bool Success { get; set; }
}
答案 0 :(得分:4)
使用JSON.NET,您可以编写自定义JSON转换器。例如,您可以拥有以下对象:
public class Root
{
public string Status { get; set; }
public Result Result { get; set; }
}
public class Result
{
public bool? Value { get; set; }
public Item[] Items { get; set; }
}
public class Item
{
public string Name { get; set; }
public string UserIdentifier { get; set; }
public string MaxAccounts { get; set; }
}
并且您的JSON将被反序列化为Root[]
。
以下是自定义JSON转换器的外观:
public class ResultConverter: JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Result);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Boolean)
{
return new Result
{
Value = (bool)reader.Value,
};
}
return new Result
{
Items = serializer.Deserialize<Item[]>(reader),
};
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// If you want to support serializing you could implement this method as well
throw new NotImplementedException();
}
}
然后:
class Program
{
static void Main()
{
var json =
@"[
{
""status"": ""ok"",
""result"": true
},
{
""status"": ""ok"",
""result"": [
{
""name"": ""John Doe"",
""UserIdentifier"": ""abc"",
""MaxAccounts"": ""2""
}
]
}
]";
var settings = new JsonSerializerSettings();
settings.Converters.Add(new ResultConverter());
Root[] root = JsonConvert.DeserializeObject<Root[]>(json, settings);
// do something with the results here
}
}
答案 1 :(得分:0)
使用Api和Results对象创建和arraylist。我刚试过这个并且有效。
var api = new Api();
var result = new Result();
api.Status = "ok";
api.Success = true;
result.Name = "John Doe";
result.UserIdentifier = "abc";
result.MaxAccounts = "2";
api.Result = new Result[1];
api.Result[0] = result;
var arrayList = new ArrayList() { new {api.Status, api.Success},
new { api.Status, api.Result} };
var json = JsonConvert.SerializeObject(arrayList, Formatting.Indented);