问题描述
尝试将类类型的对象添加到 JArray 时出现以下错误.
I got the following error while trying to add an object of type class to the JArray.
无法确定类型Class"的 JSON 对象类型
这是我正在使用的代码:
Here is the code that I am using:
private dynamic _JArray = null
private JArray NArray(Repository repository)
{
_JArray = new JArray();
string[] amounts = repository.Amounts.Split('|');
for (int i = 0; i <= amounts.Length; i++)
{
_JArray.Add(
new AmountModel
{
Amounts = amounts[i],
});
}
return _JArray;
}
public class AmountModel
{
public string Amounts;
}
我在运行程序时这样称呼它:
And I call it like the following when run the program:
_JArray = NArray(repository);
Console.WriteLine(JsonConvert.SerializeObject(_JArray));
如何将_JArray (JArray)中的AmountModel (class)转换为JSON对象?
How can I convert the AmountModel (class) inside of _JArray (JArray), to be recognized by the system as JSON object?
非常感谢您的回答.
谢谢.
推荐答案
为了将任意非原始 POCO 添加到 JArray
(或 JObject
),您必须使用 JToken.FromObject() 的重载之一显式序列化它
:
In order to add an arbitrary non-primitive POCO to a JArray
(or JObject
), you must explicitly serialize it, using one of the overloads of JToken.FromObject()
:
_JArray = new JArray();
string[] amounts = repository.Amounts.Split('|');
for (int i = 0; i < amounts.Length; i++)
{
_JArray.Add(JToken.FromObject(
new AmountModel
{
Amounts = amounts[i],
}));
}
return _JArray;
(另请注意,我更正了 for
循环中的结束条件.它是 i <= amount.Length
,导致 IndexOutOfRangeException
异常.)
(Note also that I corrected the end condition in your for
loop. It was i <= amounts.Length
, which resulted in an IndexOutOfRangeException
exception.)
工作示例 .Net fiddle #1 这里.
Working sample .Net fiddle #1 here.
或者,您可以使用 LINQ 和 JArray.FromObject 简化代码()
通过将字符串数组投影到 AmountModel
可枚举然后在一次调用中将整个序列序列化为 JArray
:
Alternatively, you could simplify your code with LINQ and JArray.FromObject()
by projecting the string array to an AmountModel
enumerable then serializing the entire sequence to a JArray
in one call:
var _JArray = JArray.FromObject(amounts.Select(a => new AmountModel { Amounts = a }));
小提琴示例 #2 这里.
这篇关于无法确定类型“Class"的 JSON 对象类型.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!