简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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