3

I have a POCO object like this -

class User
{
     string FullName { get; set;}
     DateTime DOJ { get; set;}
     string UserName { get; set;}
}

I have a WebAPI that sends following JSON to update user

PUT /user/{user-id}
{
    "FullName ": "My Name",
    "DOJ": "01-05-2018",
    "UserName": "My_user_Name"
}

// Deserialize in C# code
var user = JsonConvert.DeserializeObject<User>(Above-Json-String);

When i deserialize this json using JSON.net apis, value for "user.UserName" is "My user Name", the underscores got converted into space.

Any solution to preserve underscores in the property value?

7
  • 2
    I just tried deserializing from a string constant and the underscores were preserved. So I don't think it's the deserialization that does it. Could it be something in the transport layer that changes them to spaces? Quick test: See if your JSON string has the underscores before deserialization. Commented Jan 5, 2018 at 7:04
  • please check this link Commented Jan 5, 2018 at 7:09
  • @sunrise: That's in the property name, not the value. Commented Jan 5, 2018 at 8:10
  • I think stackoverflow.com/questions/47948266/… will help you Commented Jan 5, 2018 at 8:53
  • @Hans - Thanks for your reply. I tried your test and i can see underscores before deserialization. So its passing through transport layer. BTW, what version of library are you using? i am using "8.0.3.19514" and i cant change to higher versions because of business reasons. Commented Jan 5, 2018 at 9:39

1 Answer 1

3

Jsonproperty might solve your issue stated.

Use the JsonProperty attribute to indicate the name in the JSON.

[JsonProperty(PropertyName = "binding type")]
string FullName { get; set;}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.