2017-10-11 30 views
0
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对象像如何将数组(字符串[])转换为JsonValue?

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

不要使用JavaScriptSerializer。已经过时了。微软本身使用Json.NET –

回答

0

可以使用JavaScriptSerializer代替声明JsonObject

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

您可以使用

JObject json = JObject.Parse(str); 

请参阅this

1

创建一个包含“Array”属性的包装类。这将允许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; } 
} 

注意,这里采用Json.NET,您可以下载/在这里进一步了解更多的信息:https://www.newtonsoft.com/json

+0

好吧。但是如何生成这样的json: {“some_field”:true,“array”:[“first_value”,“second_value”,“third_value”]“} –

+0

@ J.Huxley查看更新 –

0

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

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

所以没有包装等等json -string正在寻找这样的:

[ 
    "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" 
     ] 
    } 
} 
相关问题