将JSON单个字符串反序列化为数组 [英] Deserialize JSON single string to array
问题描述
我正在尝试反序列化json数据,但是我的班级设置不正确,我无权更改json响应,因此我需要编写一个函数来正确处理json.
I am trying to deserialize my json data however my class is not set up properly I do not have access to change the json response, so I need to write a function to handle the json properly.
这里是数据
{
"blabla": {
"-Score": "1",
"-Ref": "50",
"foo": {
"-colour": "Yellow",
"-ref": "y50"
}
}
}
有时数据会
{
"blabla": {
"-Score": "1",
"-Ref": "50",
"foo": [
{
"-colour": "Yellow",
"-ref": "y50"
},
{
"-colour": "Green",
"-ref": "g50"
},
{
"-colour": "Red",
"-ref": "r50"
}
]
}
}
该类适用于第一个数据
public class blabla
{
public Foo Foo {get; set;}
}
该类适用于第二个数据
public class blabla
{
public Foo[] Foo {get; set;}
}
但是我如何让这门课对两者都起作用?
But how can I get the class to work for both?
推荐答案
以下是基本类:
public class Test
{
public Blabla blabla { get; set; }
}
public class Blabla
{
public string _score { get; set; }
public string _ref { get; set; }
[JsonConverter(typeof(FooConverter))]
public Foo[] foo { get; set; }
}
public class Foo
{
public string _colour { get; set; }
public string _ref { get; set; }
}
无论数据是什么,都将foo
的类型设置为Foo[]
,并添加[JsonConverter(typeof(FooConverter))]
以使用自定义转换器.
Set type of foo
to be Foo[]
no matter what the data is, and add [JsonConverter(typeof(FooConverter))]
to use a custom converter.
这是自定义转换器:
public class FooConverter : JsonConverter
{
// Declared as abstract in JsonConverter so must be overridden
public override bool CanConvert(Type objectType) { return true; }
// Declared as abstract in JsonConverter so must be overridden
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
return token.Type == JToken.Array ? token.ToObject<Foo[]>() : new Foo[] { token.ToObject<Foo>() };
}
}
在ReadJson
方法中,我们将数据加载到令牌中,然后检查数据是数组还是普通对象.如果已经是一个数组,则只将数组对象返回为Foo[]
;如果它是一个普通对象,则返回一个包含普通对象的new Foo[]
.
In the ReadJson
method we load the data in a token and we check whether the data is an array or a plain object. If it is already an array we just return the array object as Foo[]
and if it is a plain object we return a new Foo[]
containing our plain object.
这是一个测试用例:
string json1 = @"{
""blabla"":
{
""_score"": ""1"",
""_ref"": ""50"",
""foo"":
{
""_colour"": ""Yellow"",
""_ref"": ""y50""
}
}
}";
string json2 = @"{
""blabla"":
{
""_score"": ""1"",
""_ref"": ""50"",
""foo"":
[
{
""_colour"": ""Yellow"",
""_ref"": ""y50""
},
{
""_colour"": ""Green"",
""_ref"": ""g50""
},
{
""_colour"": ""Red"",
""_ref"": ""r50""
}
]
}
}";
Test test1 = JsonConvert.DeserializeObject<Test>(json1);
Test test2 = JsonConvert.DeserializeObject<Test>(json2);
您将始终拥有一个数组,但是第一个测试用例中将有1个元素,而第二个测试用例中将有3个元素.
You will always have an array but there will be 1 element in the first test case, and 3 elements in the second test case.
这篇关于将JSON单个字符串反序列化为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!