如何使用Json.NET序列化和反序列化数组的ArrayList



我需要在应用程序中使用json.NET将对象序列化/反序列化为json。对象的属性类型为ArrayList,其中包含字符串数组。为了模拟它,我编写了以下单元测试;

public class JsonTests
{
public class MyTestClass
{
public ArrayList Items { get; private set; }
public MyTestClass()
{
this.Items = new ArrayList();
}
}
[Fact]
public void JsonConvert_Should_Serialize_ArrayList_And_Deserialize_Successfully()
{
MyTestClass myObject = new MyTestClass();
myObject.Items.Add(new string[] { "Test1", "Test2" });
string jsonResult = JsonConvert.SerializeObject(myObject);            
MyTestClass tempMyObject = JsonConvert.DeserializeObject<MyTestClass>(jsonResult);
//(tempMyObject.Items[0] as string[]) casts to null therefore it throws exception
Assert.Equal((myObject.Items[0] as string[])[0], (tempMyObject.Items[0] as string[])[0]);
} 
}

它在序列化过程中不会抛出任何异常。但是,它没有正确地反序列化ArrayList。

我的问题是,如何将它反序列化回字符串数组的ArrayList?

更新:此外,我不能更改类定义。该类是在程序集中实现的,在该程序集中我无法编辑该类。

ArrayList是一个非泛型、非类型化的集合,因此您需要将预期的项类型通知Json.NET。一种方法是为ArrayList:使用自定义JsonConverter

public class ArrayListConverter<TItem> : JsonConverter
{
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var list = serializer.Deserialize<List<TItem>>(reader);
var arrayList = existingValue as ArrayList ?? new ArrayList(list.Count);
arrayList.AddRange(list);
return arrayList;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ArrayList);
}
}

然后将转换器应用于类,如下所示:

public class MyTestClass
{
[JsonConverter(typeof(ArrayListConverter<string []>))]
public ArrayList Items { get; private set; }
public MyTestClass()
{
this.Items = new ArrayList();
}
}

样品小提琴。

如果类无法修改,并且您希望对象图中ArrayList的所有实例将其项反序列化为string [],则可以将转换器添加到JsonSerializerSettings.Converters,而不是添加到类型:

var tempMyObject = JsonConvert.DeserializeObject<MyTestClass>(jsonResult,
new JsonSerializerSettings { Converters = { new ArrayListConverter<string []>() } });

样品小提琴#2。

最后,如果不能修改类,并且只希望MyTestClass中的特定ArrayList Items属性将其项反序列化为string [],则需要为MyTestClass创建一个自定义转换器。您只能将来自Custom反序列化程序的模式用于带有json的某些字段。NET自定义反序列化ArrayList属性,同时用默认的反序列化填充剩余部分:

public class MyTestClassConverter : JsonConverter
{
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var root = existingValue as MyTestClass ?? (MyTestClass)serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
var jsonObject = JObject.Load(reader);
var jsonItems = jsonObject["Items"].RemoveFromLowestPossibleParent();
if (jsonItems != null && jsonItems.Type != JTokenType.Null)
{
root.Items.AddRange(jsonItems.ToObject<List<string []>>());
}
// Populate the remaining standard properties
using (var subReader = jsonObject.CreateReader())
{
serializer.Populate(subReader, root);
}
return root;
}
public override bool CanConvert(Type objectType)
{
return typeof(MyTestClass).IsAssignableFrom(objectType);
}
}
public static class JsonExtensions
{
public static JToken RemoveFromLowestPossibleParent(this JToken node)
{
if (node == null)
return null;
var contained = node.AncestorsAndSelf().Where(t => t.Parent is JContainer && t.Parent.Type != JTokenType.Property).FirstOrDefault();
if (contained != null)
contained.Remove();
// Also detach the node from its immediate containing property -- Remove() does not do this even though it seems like it should
if (node.Parent is JProperty)
((JProperty)node.Parent).Value = null;
return node;
}
}

然后按如下方式使用:

var tempMyObject = JsonConvert.DeserializeObject<MyTestClass>(jsonResult,
new JsonSerializerSettings { Converters = { new MyTestClassConverter() } });

样品小提琴#3。

试试这个我希望这个代码能帮助你

使用ListJSON.NET

List<string[]> list = new List<string[]>();
list.Add(new string[] { "Value","value" });
list.Add(new string[] { "b2", "b22" });
var ee = JsonConvert.SerializeObject(list);
Console.WriteLine(ee);
List<string[]> ll = JsonConvert.DeserializeObject<List<string[]>>(ee);

foreach (var Valus in ll)
{
foreach (var val in Valus)
{
Console.WriteLine(val);
}
}

使用阵列列表

string[][] strarry = { new string[] { "f1", "f2", "f3" }, new string[] { "s1", "s2", "s3" }, new string[] { "t1", "t2", "t3" } };
string SerializeArray = json.Serialize(strarry);
string[][] DeSerializeArrayList = json.Deserialize<string[][]>(SerializeArray);
foreach (var item in DeSerializeArrayList)
{
foreach (var Subitem in item)
{
Response.Write(Subitem + "<br/>");
} 
}

使用列表

List<Data> list = new List<Data>();
list.Add(new Data() { ID = 1, Name = "val1" });
list.Add(new Data() { ID = 2, Name = "val2" });
JavaScriptSerializer json = new JavaScriptSerializer();
string Serialize = json.Serialize(list);
Response.Write(Serialize);
List<Data> DeSerialize = json.Deserialize<List<Data>>(Serialize);
foreach (var Data in DeSerialize)
{
Response.Write(Data.Name);
}

数据类

public class Data
{
public int ID { get; set; }
public string Name { get; set; }
}

相关内容

  • 没有找到相关文章

最新更新