2017-10-11 25 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" 
     ] 
    } 
}