Gaurav123
Gaurav123

Reputation: 5219

Deserialize json string to object in c# in Key value pair (Comma separated values)

I have below json in string as parameter to a WebMethod.

How can I deserialize in such a way that value comes in Key value pair.

Json String Parameter:

["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;
}

Upvotes: 0

Views: 6106

Answers (2)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34244

If you need to work with JSON data then use Newtonsoft.JSON library. Convert the object to an array of strings and then split every line. With this approach you can be sure that the given string is actually an JSON array and it is correct.

    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);
    }

Or this one using LINQ. It looks better and it can be written faster. However, it is less optimal (two calls of Split instead of one).

    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);
    }

Upvotes: 1

Hussein Khalil
Hussein Khalil

Reputation: 1401

why don't you just change every ',' in the string array to ':' then pass it to the method, from what you wrote in the question, this should work

Upvotes: 0

Related Questions