简体   繁体   English

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

[英]How to convert array(string[]) to JsonValue?

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

        }
    }
}

I want to receive in result Json object like 我想收到结果Json对象,例如

{"array":["first_value","second_value","third_value"]"}

Create a wrapper class that you serialize that has an "Array" property. 创建要序列化的包装器类,该包装器类具有“数组”属性。 This will allow the JSON serialized object to have the "Array" field name you are looking for. 这将使JSON序列化的对象具有您要查找的“ Array”字段名称。

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; }
}

Note, this uses Json.NET, which you can download/find more info about here: https://www.newtonsoft.com/json 请注意,这使用的是Json.NET,您可以在此处下载/找到更多信息: https : //www.newtonsoft.com/json

You can use JavaScriptSerializer instead of declaring a JsonObject 您可以使用JavaScriptSerializer而不是声明JsonObject

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

You can use 您可以使用

 JObject json = JObject.Parse(str);

Please refer this . 请参考这个

Download/install NuGet package " Newtonsoft.Json " and then try this: 下载/安装NuGet软件包“ Newtonsoft.Json ”,然后尝试以下操作:

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

So there is no Wrapper and so the json -string is looking like this: 因此没有Wrapper,因此json -string看起来像这样:

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

If you would use a warpper (Person.class) with data in it, it would look like this: 如果要使用其中包含数据的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"
        ]
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM