将json字符串反序列化为c#中的键值对对象(逗号分隔值)

本文关键字:对象 分隔 键值对 字符串 json 反序列化 | 更新日期: 2023-09-27 17:50:55

我有以下json字符串参数的WebMethod。

如何反序列化,使值出现在键值对中

参数:
["Ref No,0","Date,0","Amt,0","Sender Name,0","Sender Add,0","Beneficiary Name,0","Beneficiary Add,0","Phone,0","Secret Code,0","Secret Ans,0","Preferred Id,0"]

WebMethod:

[System.Web.Services.WebMethod]
public static string SaveMappings(string mappingData)
{
    //string str = "{'"Arg1'":'"Arg1Value'",'"Arg2'":'"Arg2Value'"}";
    //JavaScriptSerializer serializer = new JavaScriptSerializer();
    //object obj;
    //var data = serializer.Deserialize(mappingData,);
    var data = mappingData.ToArray();
    if (data != null)
    {
    }
    var d2 = mappingData.Split(',');
    if (d2!=null)
    {
    }
    return mappingData;
}

将json字符串反序列化为c#中的键值对对象(逗号分隔值)

如果你需要使用JSON数据,那么使用Newtonsoft。JSON库。将对象转换为字符串数组,然后拆分每行。使用这种方法,您可以确保给定的字符串实际上是一个JSON数组,并且它是正确的。

    var str = "['"Ref No,0'",'"Date,0'",'"Amt,0'",'"Sender Name,0'",'"Sender Add,0'",'"Beneficiary Name,0'",'"Beneficiary Add,0'",'"Phone,0'",'"Secret Code,0'",'"Secret Ans,0'",'"Preferred Id,0'"]";
    string[] objs = JsonConvert.DeserializeObject<string[]>(str);
    Dictionary<string, string> dic = new Dictionary<string, string>();
    foreach (var obj in objs)
    {
        var keyValue = obj.Split(',');
        dic.Add(keyValue[0], keyValue[1]);
    }
    foreach (var record in dic)
    {
        Console.WriteLine("{0} => {1}", record.Key, record.Value);
    }

或者这个使用LINQ。它看起来更好,而且可以写得更快。然而,它不是最优的(两次调用Split而不是一次)。

    public Dictionary<string, string> FromJsonArray(string jsonArray)
    {
        return JsonConvert.DeserializeObject<string[]>(jsonArray)
            .ToDictionary(obj => obj.Split(',')[0], obj => obj.Split(',')[1]);
    }
    // ...
    var str = "['"Ref No,0'",'"Date,0'",'"Amt,0'",'"Sender Name,0'",'"Sender Add,0'",'"Beneficiary Name,0'",'"Beneficiary Add,0'",'"Phone,0'",'"Secret Code,0'",'"Secret Ans,0'",'"Preferred Id,0'"]";
    foreach (var record in FromJsonArray(str))
    {
        Console.WriteLine("{0} => {1}", record.Key, record.Value);
    }

为什么不将字符串数组中的每个','更改为':'然后将其传递给方法,从您在问题中所写的内容来看,这应该可以工作