Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting JSON variables to lowercase in C#

I'm using the JSONPEncoderFactory,JSONPBehavior solution to enable JSONP in WCF. That's all fine, it's all set up and working well, my service returns the data correctly, no problems there.

However, I need to be able to force the JSON variable names into lowercase due to the way they are being used in JS, and this is something I haven't been able to figure out as yet.

Here is an example of my service output (the variable names and values have been changed to benign elements for this example)

{"Animals":["dog","cat","mouse"],"Owner":"Greg","Permanent":"y","ID":1,"DaysToStay":"1"}

Pretty simple right? I want the "Animals" to be "animals", and so on...

Do I need to use a json parser for this, or is it easy enough just to use a regular expression? I'd be grateful if someone could let me know how they've done this before.

Thanks!

like image 978
sidogg Avatar asked Nov 04 '22 15:11

sidogg


1 Answers

You can use this function on JavaScript:

FN = function (obj)
{
    var ret = null;
    if (typeof(obj) == "string" || typeof(obj) == "number")
        return obj;
    else if (obj.push)
        ret = [];
    else
        ret = {};

    for (var key in obj)
        ret[String(key).toLowerCase()] = FN(obj[key]);
    return ret;
};

EDIT: Deserialize a json string in a Dictionary with C#:

using System.Web.Script.Serialization;
var serializer = new JavaScriptSerializer();
var dic = serializer.Deserialize<Dictionary<string,dynamic>>(yourJSONString);

The complex fields will be deserialized into Dictionary. So you will ned a recursive function for inspect the matherialized dic.

like image 77
Adilson de Almeida Jr Avatar answered Nov 14 '22 22:11

Adilson de Almeida Jr