简体   繁体   中英

JSON serialize and deserialize C# with Partial objects

This is the final JSON object I am look for -

{
  "firstName": "John",
  "lastName": "Smith",
  "age": 27,
  "address": {
    "streetAddress": "21 2nd Street",      
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"         <-- Added by my application
  }
}

In this example, I don't own firstName, lastName and somepart of address. My part of logic just needs to inject age and address. Is there a way to not duplicate the entire object on my side? Can I just have an object like this -

public class AdditionalAddressInfo
{
    public string postalCode { get; set; }
}

public class AdditionalUserInfo
{
    public int age { get; set; }
}

Is there a way to serialize this and add to the incoming JSON.

You can use DynamicObject for partial deserialize, so that you don't need to know about other properties:

var jsonString = @"{
                      ""firstName"": ""John"",
                      ""lastName"": ""Smith"",
                      ""address"": {
                        ""streetAddress"": ""21 2nd Street"",      
                        ""city"": ""New York"",
                        ""state"": ""NY"",     
                      }
                    }";

dynamic dynoObject = JsonConvert.DeserializeObject<dynamic>(jsonString);

//adding age
AdditionalUserInfo additionalUserInfo = new AdditionalUserInfo();
additionalUserInfo.age = 27;
dynoObject.age = additionalUserInfo.age;

//adding postalCode
AdditionalAddressInfo additionalAddressInfo = new AdditionalAddressInfo();
additionalAddressInfo.postalCode = "10021 - 3100";
dynoObject.address.postalCode = additionalAddressInfo.postalCode;

var newJson = JsonConvert.SerializeObject(dynoObject);

Then new Json would be as expected:

{
  "firstName": "John",
  "lastName": "Smith",
  "age": 27,
  "address": {
    "streetAddress": "21 2nd Street",      
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"       
  }
}

You could directly add the new values to Json by modifying the JObject. For example,

var jObj = JObject.Parse(json);
var address = jObj["address"] as JObject;
address.Add("postalCode","10021-3100");
jObj.Add("age",27);
var result = jObj.ToString();

Output

{
  "firstName": "John",
  "lastName": "Smith",
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  },
  "age": 27
}

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