使用Json.NET将JObject转换为Dictionary <string,string =“”>

时间:2019-04-19 06:32:38

标签: c# json.net

使用JSON进行如下测试:

{\"key1\":\"value1\",\"key2\":\"value3\",\"key3\":[\"value4\"],\"key5\":\"value5\"}\n;
  

无效的参数异常:   'Newtonsoft.Json.JsonConvert.DeserializeObject>(字符串)'

这是我的代码:

string json = "{\"action\":\"recognition\",\"command\":\"event\",\"eventid\":[\"1108\"],\"from_ip\":\"192.168.0.49\",\"user\":\"safetymaster\"}\n";
json = json.Replace("\n", "");  

var DeserializedJson= JsonConvert.DeserializeObject<dynamic>(json);                                
Dictionary<string, string> jsonDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(DeserializedJson);

3 个答案:

答案 0 :(得分:1)

尝试一下。

class Program
{
    static void Main(string[] args)
    {
        try {
            string json = "{\"action\":\"recognition\",\"command\":\"event\",\"eventid\":[\"1108\"],\"from_ip\":\"192.168.0.49\",\"user\":\"safetymaster\"}\n";
            json = json.Replace("\n", "");
            RootObject m = JsonConvert.DeserializeObject<RootObject>(json);
            string ipAddress = m.from_ip;
            string eventID = m.eventid[0];

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

    }
}

根据JSON对象定义一个类。

public class RootObject
{
    public string action { get; set; }
    public string command { get; set; }
    public List<string> eventid { get; set; }
    public string from_ip { get; set; }
    public string user { get; set; }
}

答案 1 :(得分:0)

您可以简单地获取价值:

 string json = "{\"action\":\"recognition\",\"command\":\"event\",\"eventid\":[\"1108\"],\"from_ip\":\"192.168.0.49\",\"user\":\"safetymaster\"}\n";            
 var jsonData = JsonConvert.DeserializeObject<JObject>(json);
 var action = jsonData["action"].ToString();

答案 2 :(得分:0)

这可以通过两个步骤完成:

  1. 序列化为字典的<字符串,对象>
  2. 使用System.Linq功能(ToDictionary)将先前的结果转换为Dictionary

例如:

string json = "{\"action\":\"recognition\",\"command\":\"event\",\"eventid\":[\"1108\"],\"from_ip\":\"192.168.0.49\",\"user\":\"safetymaster\"}\n"; json = json.Replace("\n", "");

Dictionary<string, object> jsonDic = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

var jsonDic2 = jsonDic.ToDictionary(
    x => x.Key, 
    x => x.Value.ToString()
);

jsonDic2中的上述结果是一个包含以下内容的字典:

enter image description here

请注意:“ eventid”字典条目的字符串值的格式设置为JSON数组,因此您可能需要在必要时将其值转换为字符串数组:

var eventIdList = jsonDic2.ContainsKey("eventid")
    ? Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>(jsonDic2["eventid"])
    : new string[]{};