如何转换相等"="的字符串在c#中签名到json

本文关键字:quot 字符串 json 转换 何转换 | 更新日期: 2023-09-27 17:52:17

我有以下字符串,它从web服务返回

"Status=Success,PNR=76UUEI78787870,Customer_Ref=89511133545"

我想把它转换成json,就像下面的

{
    "Status": "Success",
    "PNR": "76UUEI78787870",
    "Customer_Ref": "89511133545"
}

如何转换相等"="的字符串在c#中签名到json

var str = "Status=Success,PNR=76UUEI78787870,Customer_Ref=89511133545";
var vals = str.Split(',');
var json = "{" +
            string.Join(",",
                vals.Select(val => val.Split('=')).Select(s => string.Format("'"{0}'": '"{1}'"", s[0], s[1]))) +
            "}";

尝试使用JavaScriptSerializer:

的代码
var paramList = "Status=Success,PNR=76UUEI78787870,Customer_Ref=89511133545";
var dict = paramList.Split(',').Select(x => x.Split('=')).ToDictionary(x => x[0], x => x[1])
var json = new JavaScriptSerializer().Serialize(dict);

这可能对您有用

private static string format_json(string json)
{
    json = json.Replace('=',":");
    dynamic parsedJson = JsonConvert.DeserializeObject(json);
    return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}

这将适用于newtonsoft.Jsonjson.net

您可以将给定的字符串转换为Dictionary并使用Json.Net进行序列化,如下所示。

string s =  @"Status=Success,PNR=76UUEI78787870,Customer_Ref=89511133545";
var dictionary = s.Split(',')   // create a dictionary.
 .Select(x=>x.Split('='))
 .ToDictionary(x=>x[0], x=>x[1]);   
string json = JsonConvert.SerializeObject( dictionary, new KeyValuePairConverter( ) );
//output 
// {"Status":"Success","PNR":"76UUEI78787870","Customer_Ref":"89511133545"}

检查fiddle

考虑使用StringBuilder(特别是如果性能很重要并且将来需要处理更大的字符串)。

        string sourceString = "Status=Success,PNR=76UUEI78787870,Customer_Ref=89511133545";
        StringBuilder bufferString = new StringBuilder();
        bufferString.Append("{'"").Append(sourceString)
            .Replace(",", "'",'"")
            .Replace("=", "'": '"")
            .Append("'"}");
        string outputString = bufferString.ToString();
        /*
         * libraries like Newtonsoft.Json NuGet package could help prettify the output string if needed
        */
        string prettyJSON = JValue.Parse(bufferString.ToString()).ToString(Formatting.Indented);

注意:这始终优于使用字符串方法。