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?

smhetre
  • 369
  • 5
  • 5
  • 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. – Hans Kilian Jan 05 '18 at 07:04
  • please check this [link](https://stackoverflow.com/questions/47589794/newtonsoft-json-replacing-spaces-with-underscores-c-sharp-to-json-serialize) – Suraj Jan 05 '18 at 07:09
  • @sunrise: That's in the property *name*, not the *value*. – Jon Skeet Jan 05 '18 at 08:10
  • I think https://stackoverflow.com/questions/47948266/c-sharp-json-to-array-debugging-application-went-to-break-mode/47948781#47948781 will help you – RICKY KUMAR Jan 05 '18 at 08: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. – smhetre Jan 05 '18 at 09:39
  • @smhetre I'm using 10.0.3 and the code I used is var user = JsonConvert.DeserializeObject("{\"FullName\": \"My Name\", \"DOJ\": \"01-05-2018\", \"UserName\": \"My_user_Name\"}"); – Hans Kilian Jan 05 '18 at 09:59
  • I just tried with 8.0.3 and that works for me as well... Strange... – Hans Kilian Jan 05 '18 at 10:10

1 Answers1

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;}