I have a problem with the Names of my deserialized object, which I want to return.
At the moment I am writing a WebService, which requests data from another WebService and then returns this Data to an Application.
Example:
public class UserController
{
public HttpResponseMessage GetUser()
{
// Get Data from WebService
string jsonString = @"{'key': 'A45', 'field1': 'John', 'field2': 'Doe', address{'field3': 'HelloWorld Ave.', 'field4': 'Somewhere'}}";
// Make Object from JSON-String
User user = JsonConvert.DeserializeObject<User>(jsonString);
// Return Object to Application
return Request.CreateResponse(HttpStatusCode.OK, user);
}
}
public class User
{
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("field1")]
public string FirstName { get; set; }
[JsonProperty("field2")]
public string LastName { get; set; }
[JsonProperty("address")]
public Address Address { get; set; }
}
public class Address
{
[JsonProperty("field3")]
public string Street { get; set; }
[JsonProperty("field4")]
public string City { get; set; }
}
So far so good. My WebService creates the Object "User" and returns it to the Application.
And now my problem:
The returning JSON string changes the field names back to its original name.
Instead of:
"{'key': 'A45', 'field1': 'John', 'field2': 'Doe', Address {'Street': 'HelloWorld Ave.', 'City': 'Somewhere'}}"
I get:
"{'key': 'A45', 'field1': 'John', 'field2': 'Doe', Address {'Street': 'HelloWorld Ave.', 'City': 'Somewhere'}}"
I know that the PropertyName in JsonProperty is not Case-Sensitive, so I could write [JsonProperty("Key")] with an uppercase "K" and the returning Json-String will contain the Uppercase "K".
But what about my fields? Is there any way I can change "field1" to "FirstName", and "field2" to "LastName"?
Edit 1 - 2015-01-28: Added more code to the example.