简体   繁体   中英

Serializing, Deserializing C#/JSON objects and not having casing issues

When I am writing Javascript functions, I believe that the convention is to use pascalCase for property names (lower first letter of first word), but when creating a C# property, it should be CamelCase (first letter of every word capitalized.) However, both languages are case sensitive and this causes an issue when serializing a Javascript or C# object to JSON and back because of the case mismatch.

I am content with the approach of adding Attributes on my C# objects to map the C# CamelCase property to the Javascript pascalCase form; it seems clean, explicit and allows me to maintain the "always case this way" approach while writing within each language and this I feel helps me cut down on errors and I like consistency. However, for objects that are generated, eg, Entity Framework objects, these objects are generated without these attributes and if I were to add them and then decide to regenerate to pick up database changes, I would lose the attributes. (I am using visual Studioo, ASP.NET MVC and reverse engineeering Code "First" from a database.)

I am a rookie at all of these technologies. I would like your advise on how to serialize these objects easily so that I can consistantly use the desired casing even with generated objects. Is there a way to have it all in this case?

There's a lot of questions on this subject, but I'm not sure that this particular angle has been addressed.

Here's a contrived example where I play to try and learn about these subjects:

function Person(name, age) 
{
    this.name = name;
    this.age = age;
    return this;
}


$(document).ready(function () {

    /* Finds all of the controls whose IDs begin with PushMeButton */
    $("[id^=PushMeButton]").click(function () {

        //var id = $(this).attr('id');

        var url = '/Home/Ajax/';
        var joe = new Person("Joe", 98);

        $.ajax({
            type: 'POST',
            url: url,
            dataType: 'json',
            data: joe,
            success: function (person) {
                alert('im back');
                alert(person.age);
            },
            error: function (xhr, ajaxOptions, error) {
                alert(xhr.status);
                alert('Error: ' + xhr.responseText);
            }
        });
    });
});

//Server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Restaurant.Data;

namespace MyApp.Controllers
{
    public class Person
    {
        [JsonProperty(PropertyName = "name")]
        public string Name
        {
            get;
            set;
        }

        [JsonProperty(PropertyName = "age")]
        public int Age
        {
            get;
            set;
        }
    }

    public class HomeController : Controller
    {
        [HttpPost]
        public string Ajax(Person person)
        {
            person.Name = "Mr. " + person.Name;
            person.Age += 10;
            string personJson = JsonConvert.SerializeObject(person);

            return personJson;
        }
    }
}

You can use the ContractResolver property of the JsonSerializerSettings class:

var settings = new JsonSerializerSettings{ ContractResolver = new CamelCasePropertyNamesContractResolver()  };
var s = JsonConvert.SerializeObject(object, settings);
var newObject = JsonConvert.DeserializeObject<type>(s, settings);

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