无法确定类型"Class"的JSON对象类型. [英] Could not determine JSON object type for type "Class"

查看:232
本文介绍了无法确定类型"Class"的JSON对象类型.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试将类类型的对象添加到 JArray 时遇到以下错误.

I got the following error while trying to add an object of type class to the JArray.

Could not determine JSON object type for type "Class"

这是我正在使用的代码:

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(类),以使系统识别为JSON对象?

How can I convert the AmountModel (class) inside of _JArray (JArray), to be recognized by the system as JSON object?

非常感谢您的回答.

谢谢.

推荐答案

为了向JArray添加任意非原始POCO,必须使用

In order to add an arbitrary non-primitive POCO to a JArray, 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 <= amounts.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小提琴#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对象类型.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆