如何将数组(string [])转换为JsonValue?

时间:2017-10-11 15:28:34

标签: c# json

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Json;

namespace StackOverflowQuestion
{
    class StackOverflowQuestion
    {
        public StackOverflowQuestion()
        {
            JsonObject  jsonObj = new JsonObject();
            string[] arr = { "first_value", "second_value", "third_value"          };
            obj.Add("array", arr ); // Compiler cannot convert string[] to System.Json.JsonValue

        }
    }
}

我想在结果中收到像

这样的Json对象
{"array":["first_value","second_value","third_value"]"}

4 个答案:

答案 0 :(得分:1)

创建一个序列化的包装类,它具有"数组"属性。这将允许JSON序列化对象具有"数组"您正在寻找的字段名称。

var array = { "first_value", "second_value", "third_value" };
var json = JsonConvert.SerializeObject(new JsonArray
{
    Array = array,
    Some_Field = true
});

public class JsonArray
{
    public string[] Array { get; set; }

    public bool Some_Field { get; set; }
}

注意,这使用Json.NET,你可以在这里下载/找到更多信息:https://www.newtonsoft.com/json

答案 1 :(得分:0)

您可以使用JavaScriptSerializer代替声明JsonObject

string[] arr = { "first_value", "second_value", "third_value"          };
new JavaScriptSerializer().Serialize(arr)

答案 2 :(得分:0)

您可以使用

 JObject json = JObject.Parse(str);

请参阅this

答案 3 :(得分:0)

下载/安装NuGet包“ Newtonsoft.Json ”,然后试试这个:

string[] arr = { "first_value", "second_value", "third_value"};
var json = JsonConvert.SerializeObject(arr);

所以没有Wrapper,所以json - 字符串看起来像这样:

[
   "first_value",
   "second_value",
   "third_value"
]

如果您使用包含数据的warpper(Person.class),它将如下所示:

// Structure....
Person
   private String name;
   private String lastName;
   private String[] arr;   // for your example...

JsonConvert.SerializeObject(person);
{
    "Person": {
        "name": "<VALUE>",
        "lastName": <VALUE>,
        "arr":[
             "first_value",
             "second_value",
             "third_value"
        ]
    }
}
相关问题