With NewtonSoft, how to create an array of strings with JArray

好久不见. 提交于 2020-01-07 01:49:27

问题


I've got the following code that returns an aggregate exception. I essentially want to create what will be a simple list of strings.

        JArray jArray = new JArray();
        foreach (string id in recipientIds)
        {
            var jsonObject = JObject.FromObject( (String)id);
            jArray.Add(jsonObject);
        }

The above works when id is a class with setters and getters but not when id is a string.


回答1:


JToken.FromObject() will work for primitives and collections as well as classes:

var jArray = new JArray(recipientIds.Select(s => JToken.FromObject(s)));



回答2:


Using JArray:

var recipientIds = new[] {"something", "another thing"};
var jArray = JArray.FromObject(recipientIds);


来源:https://stackoverflow.com/questions/35465163/with-newtonsoft-how-to-create-an-array-of-strings-with-jarray

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