0

I have created the following class I want to serialize into Json:

[JsonObject("user_auth")]
public class CrmAuth
{
    [JsonProperty("user_name")]
    public string Name { get; set; }
    [JsonProperty("password")]
    public string Password { get; set; }
}

I am trying to serialize it like:

var serialized = JsonConvert.SerializeObject(crmAuthInstance);

This create this json:

{
    "user_name":"login name",
    "password":"the password"
}

But what I want is this:

"user_auth" : {
    "user_name":"login value",
    "password":"password value"
}

Is there a neat way to achieve the serialization with a single class like this?

Guerrilla
  • 13,375
  • 31
  • 109
  • 210
  • Have you checked this post http://stackoverflow.com/questions/16294963/json-net-serialize-object-with-root-name – Rahul Aug 07 '16 at 22:04

2 Answers2

0

test this command

var serialized = JsonConvert.SerializeObject(new{user_auth=crmAuthInstance});
shady youssery
  • 430
  • 2
  • 17
  • Is there any way to define it at the class level or does it have to be done from the calling code? I'd really like to define this on the actual class models – Guerrilla Aug 07 '16 at 22:03
0

I've got it working like this:

public class CrmAuthReq
{
    [JsonProperty("user_auth")]
    public CrmAuth Auth { get; set; }
}
public class CrmAuth
{
    [JsonProperty("user_name")]
    public string Name { get; set; }
    [JsonProperty("password")]
    public string Password { get; set; }
}
Guerrilla
  • 13,375
  • 31
  • 109
  • 210