Could not determine JSON object type for type “Class”

后端 未结 1 1275
既然无缘
既然无缘 2020-12-20 10:57

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\"

相关标签:
1条回答
  • 2020-12-20 12:01

    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.

    0 讨论(0)
提交回复
热议问题