Failed to determine JSON object type for class type

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

Could not determine JSON object type for type "Class"

Here is the code I'm 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 when I call the program, I call it like this:

_JArray = NArray(repository);

Console.WriteLine(JsonConvert.SerializeObject(_JArray));

How can I convert an AmountModel (class) inside _JArray (JArray) so that the system recognizes a JSON object?

I really liked your answer.

Thank.

+7
source share
1 answer

To add an arbitrary non-primitive POCO to JArray, you must explicitly serialize it using one of the overloads : 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.)

.Net № 1 .

, LINQ JArray.FromObject(), AmountModel JArray :

var _JArray = JArray.FromObject(amounts.Select(a => new AmountModel { Amounts = a }));

№2 .

+14

Source: https://habr.com/ru/post/1661467/


All Articles