反序列化存储在字符串变量中的Json String

时间:2017-09-28 14:12:25

标签: json

我在VS 2015和c#工作。

我有一个Json String,它有一个集合列表,每个集合代表一个对象,

string wsjson = 
"{
"customAttributes":
    [{"description":"xxxxxxx","id":11,"value":"xxxxxxx"},{"description":"xxxxxxx","id":10,"value":"xxxxxxx"}],
"location":{"account":"xxxxxxx","cabinet":"xxxxxxx"},
"misc":{"approved":false,"archived":false,"deleted":false,"echo":true,"external":false,"favorite":false,"officialLocked":false,"signed":false},
"permissions":[{"xxxxxxx":true,"xxxxxxx":false,"edit":true,"noAccess":false,"share":true,"view":true}],
"standardAttributes":{"aclStatus":"xxxxxxx","created":"\/Date(xxxxxxx)\/","createdBy":"xxxxxxx","createdByGuid":"xxxxxxx","envId":"xxxxxxx","extension":"ndws","id":"xxxxxxx","modified":"\/Date(xxxxxxx)\/","modifiedBy":"xxxxxxx","modifiedByGuid":"xxxxxxx","name":"xxxxxxx","officialVer":1,"size":4,"syncMod":xxxxxxx,"url":"xxxxxxx","versions":1}}"

DataSet wsdataSet = JsonConvert.DeserializeObject<DataSet>(wsjson);

我收到了错误消息。我试图遵循这个(Deserializing Json String into multiple Object types)解决方案,但我收到此行的错误,因为我的jason数据是一个字符串,没有解析字符串的函数。

var j = JArray.Parse(data);

以下是杰森数据的视觉图像。

enter image description here

我程序中的实际代码块是:

foreach (DataRow row in dataTable.Rows)
                {
                    string wsjson = GetWorkspaceProfile(row[0].ToString());                   
                    DataSet wsdataSet = JsonConvert.DeserializeObject<DataSet>(wsjson);
                    DataTable wsdataTable = wsdataSet.Tables["standardAttributes"];
                    foreach (DataRow wsrow in wsdataTable.Rows)
                    {
                        cmbWorkspaceByCabinet.Items.Add(new KeyValuePair<string, string>(row["envId"].ToString(), wsrow["name"].ToString()));
                    }
                }

其中GetWorkspaceProfile是一个字符串类型返回函数,它将JSON数据作为字符串返回,如上图所示。

public string GetWorkspaceProfile(string WorkspaceId)
        {
            string responseStr = "";
            string url = "v1/Workspace/" + WorkspaceId + "/info";

            RestType type = RestType.GET;
            Boolean useXml = false;
            RestRequest rr = FormRequest(type, url, useXml);
            IRestResponse response;
            try
            {
                response = executeRequest(rr);
                responseStr = response.Content;
            }
            catch (Exception ex)
            {

                return null;
            }
            return responseStr;
        }

1 个答案:

答案 0 :(得分:1)

=IFERROR(VLOOKUP(A2,$H$1:$I$10,2,FALSE),0)不起作用,因为你没有json数组,它是一个对象。此外,该对象的所有值都不是集合,例如JArray.Parse也是对象,而不是集合。你有一些解析它的选项

  1. 将根对象解析为location

    Dictionary

    然后,如果value是数组,则将字典的每个值解析为数组;如果value是object,则解析为字典。

  2. 根据您的json数据创建一个C#类,并将字符串直接解析为该类的实例

    JsonConvert.DeserializeObject<Dictionary<string, string>>(wsjson)
    

    其中JsonConvert.DeserializeObject<JsonModel>(wsjson); 是您需要创建的类。

  3. 您可以使用JsonModelJArray使用json路径获取所需的值。