Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

c# - Could not determine JSON object type for type "Class"

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...