如何将匿名数组转换为C#类
大家好,
我有一个json喜欢以下
Hi All,
I am having a json like following
["G6863","2010368363","201030821","NewData","Latest"]
我想将上面的JSON转换为f#的c#类
I want to Convert the above JSON to c# classs of fallowng
public Class classified{
public string GId{set;get}
public string UID{set;get}
public string UDATE{set;get}
public string MESSAGE{set;get}
public string UPDATEREASON{set;get}
}
i希望它是通用的,因为我需要将它写入许多文件
我尝试过:
所以我尝试了以下
i want to be it generic as i need to write it to many files
What I have tried:
so i tried the following
var SerializedText=["G6863","2010368363","201030821","NewData","Latest"]
JsonConvert.DeserializeObject(SerializedText, typeof(classified)) as classified
但它会抛出一个错误的错误
无法反序列化当前的JSON数组(例如[1,2,3])类型'分类',因为类型需要一个JSON对象(例如{name:value})才能正确反序列化。
修复此错误要么改变JSON到JSON对象(例如{name:value})或将反序列化类型更改为数组或实现集合接口的类型(例如ICollection,IList),如List< t>可以从JSON数组反序列化。 JsonArrayAttribute也可以添加到类型中以强制它从JSON数组反序列化。
路径'',第1行,位置1.
but it is throwing fallowing error
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'classified' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<t> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
对于这样的要求,您可以使用类构造函数。请参阅:构造函数(C#编程指南)| Microsoft Docs [ ^ ]
For such of requirements you can use class constructor. See: Constructors (C# Programming Guide) | Microsoft Docs[^]