简体   繁体   English

将字典转换为Json?

[英]Converting dictionary to Json?

I'm trying to convert my dictionary to JSON. 我正在尝试将字典转换为JSON。 I have a client server application set and I'm trying to create an outgoing packet on the server side, but I have the packet data in a dictionary. 我有一个客户端服务器应用程序集,正在尝试在服务器端创建一个传出数据包,但是该数据包的数据在字典中。

My dictionary structure is set up something like this. 我的字典结构设置如下。

"device.name" => "Machine-39FK394S"
"device.username" => "admin"
"device.operating_system" => "Windows 10"
"something.else" => 294

A dot represents another level in JSON, the output in JSON would be like this. 点表示JSON中的另一个级别,JSON中的输出将是这样。

{
    "device" : {
        "name" : "Machine-39FK394S",
        "username" : "admin",
        "operating_system" : "Windows 10",
    }

    "something" : {
        "else" : 294,
    }
}

What have I tried so far? 到目前为止,我尝试了什么?

public string GetJson()
{
    var entries = _packetData.Select(d => string.Format("\"{0}\": [{1}]", d.Key, string.Join(",", d.Value)));
    return "{" + string.Join(",", entries) + "}";
}

Although the above method just outputs an empty {} json string. 尽管上述方法仅输出一个空的{} json字符串。

How about something like this, it should work for any number of properties: 这样的事情怎么样,它应该适用于许多属性:

var inputDict = new Dictionary<string, object>();

inputDict["device.name"] = "Machine-39FK394S";
inputDict["device.username"] = "admin";
inputDict["device.operating_system"] = "Windows 10";
inputDict["something.else"] = 294;

var outputObject = new Dictionary<string, object>();

foreach (var kvp in inputDict)
{
    var currentDict = outputObject;
    var depth = 0;
    var fields = kvp.Key.Split('.');

    foreach (var field in fields)
    {
        if (++depth == fields.Length)
        {
            currentDict[field] = kvp.Value;
        }
        else if (!currentDict.ContainsKey(field))
        {
            currentDict[field] = new Dictionary<string, object>();
        }
        currentDict = currentDict[field] as Dictionary<string, object>;
    }
}

var json = JsonConvert.SerializeObject(outputObject, Formatting.Indented);
Console.WriteLine("JSON: " + json);

I get the output below: 我得到以下输出:

{
  "device": {
    "name": "Machine-39FK394S",
    "username": "admin",
    "operating_system": "Windows 10"
  },
  "something": {
    "else": 294
  }
}

This uses Newtonsoft Json.Net, however I do believe it would be hard to compose this JSON without such a library. 它使用Newtonsoft Json.Net,但是我确实相信如果没有这样的库,就很难组成这个JSON。 Json.Net will handle all the conversion of various types of objects to string, plus it will handle escaping JSON delimiters. Json.Net将处理各种类型的对象到字符串的所有转换,此外还将处理转义的JSON分隔符。 Writing this type of code yourself will be very nasty. 自己编写这种类型的代码会很讨厌。 In addition it's highly customizable and will allow datetime formats etc. to be changed. 另外,它是高度可定制的,并将允许更改日期时间格式等。

You might need a little refinement to handle NULLs etc. 您可能需要进行一些改进以处理NULL等。

If you wish to avoid using Json.Net, you can add a reference to System.Web.Extensions and like so: 如果您希望避免使用Json.Net,则可以添加对System.Web.Extensions的引用,如下所示:

using System.Web.Script.Serialization;
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(outputObject);

You can use Newtonsoft.Json from NuGet to do that. 您可以使用NuGet的Newtonsoft.Json来做到这一点。 ie: 即:

var data = new 
{
    device = new 
    {
        name = "Machine-39FK394S",
        username = "admin",
        operating_system = "Windows 10"
    },
    something = new {_else=294}
};

var json = JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM