Convert a json structure in C#

Viewed 87

Need to convert the following json, using newtonsoft json or json.net in C#,

{
    "firstName": "John",
    "lastName": "Smith",
    "gender": "man",
    "age": 32,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    },
    "phoneNumbers": [
        { "type": "home", "number": "212 555-1234" },
        { "type": "fax", "number": "646 555-4567" }
    ]
}

to the following format, here the firstname is converted to name and lastName is converted to last

{"student":{
    "first": "John",
    "last": "Smith",
    "gender": "man",
    "age": 32,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    },
    "phoneNumbers": [
        { "type": "home", "number": "212 555-1234" },
        { "type": "fax", "number": "646 555-4567" }
    ]
}}
1 Answers

Newtonsoft.Json.Serialization's ContractResolver is best for this purpose without actually using a view model, define all the property-to-property mapping for json that needs to be serialized or de-serialized. Sample:

public class CustomContractResolver : DefaultContractResolver
{
    private Dictionary<string, string> PropertyMappings { get; set; }

    public CustomContractResolver()
    {
        this.PropertyMappings = new Dictionary<string, string>
        {
            {"first", "firstName"},
            {"last", "lastName"},
            //other properties if you want,
        };
    }

    protected override string ResolvePropertyName(string propertyName)
    {
        string resolvedName = null;
        var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
        return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
    }
}

Now here is how to use it:

var student = JsonConvert.DeserializeObject(jsonString, new JsonSerializerSettings{ ContractResolver = new CustomContractResolver() });

var jsonStructureRequired = JsonConvert.SerializeObject(new { student = student });
Related