Could not determine JSON object type for type “Class”

孤者浪人 提交于 2019-12-30 16:26:15

问题


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));

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

Your answer much appreciated.

Thank you.


回答1:


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;

(Note also that I corrected the end condition in your for loop. It was i <= amounts.Length, which resulted in an IndexOutOfRangeException exception.)

Working sample .Net fiddle #1 here.

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 }));

Sample fiddle #2 here.



来源:https://stackoverflow.com/questions/40722227/could-not-determine-json-object-type-for-type-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!