如何从json中的对象读取int数组(或任何数组)

时间:2018-06-05 11:51:34

标签: c# .net arrays json json.net

所以我在两个客户之间建立了工作沟通。要发送数据我使用json,一切正常,而我发送单个值,但当我尝试发送整个数组时,我不知道如何在接收部分读取它们。

    Dictionary<string, object> data = new Dictionary<string, object>();        

    data.Add("string", "some string");
    data.Add("int", 234);
    data.Add("bool", true);
    data.Add("intArray", new int[] { 1, 2, 3 });

    string jsonString = JsonConvert.SerializeObject(data);

    //sending data through internet as json string

    var newData = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);

    string myString = Convert.ToString(newData["string"]);
    int myInt = Convert.ToInt32(newData["int"]);
    bool myBool = Convert.ToBoolean(newData["bool"]);
    int[] myIntArray = (int[])newData["intArray"]; //doesn't work


    Debug.Log(myString);
    Debug.Log(myInt);
    Debug.Log(myBool);
    Debug.Log(myIntArray);

任何人都知道如何做到这一点?

1 个答案:

答案 0 :(得分:2)

您可以使用JSON.Net方法ToObject<>()

var myIntArray = ((JArray) newData["intArray"]).ToObject<int[]>();

但更简洁的方法是使用类而不是Dictionary<>()

定义班级

public class JsonData
{
    public string MyString {get;set;}
    public int MyInt {get;set;}
    public bool MyBool {get;set;}
    public int[] MyIntArray {get;set;}
}

使用课程

var myData = new JsonData{
    MyString = "some string",
    MyInt = 234,
    MyBool = true,
    MyIntArray = new[] {1,2,3}
};

string jsonString = JsonConvert.SerializeObject(myData);

//sending data through internet as json string

var newData = JsonConvert.DeserializeObject<JsonData>(jsonString);

Debug.Log(newData.MyString);
Debug.Log(newData.MyInt);
Debug.Log(newData.MyBool);
Debug.Log(newData.MyIntArray);