Home > Software design >  Custom Json Convert
Custom Json Convert

Time:08-31

I need this json format to send in a request body:

{
"add": {
    "welcome_email": [
        "new_user_consented"
    ],
    "goodby_email": [
        "new_user_unconsented"
    ]
},
"audience
": {
     "user_id": [
                    "4520303589"
                ]
            }  
        }

I created a C# class

 public class TagsRequest
{
    [JsonProperty("Tags")]
    public Dictionary<string, List<Dictionary<string, List<string>>>> Tags { get; set; }

    [JsonProperty("audience")]
    public Audience Audience { get; set; }
}

When create an object from it and serialize is I get this result:

{
  "tags": {
    "add": [
      {
        "welcome_email": [
          "new_user_consented"
        ]
      }
    ]
  },
  "audience": {
    "named_user": "joe"
  }
}

What should I do to get the proper result (the first one) from this class convertion?

Thanks advanced,

CodePudding user response:

if you want to use a dictionary your classes could be

Data data= JsonConvert.DeserializeObject<Data>(json);

public partial class Data
{
    [JsonProperty("add")]
    public Dictionary<string, List<string>> Add { get; set; }

    [JsonProperty("audience")]
    public Audience Audience { get; set; }
}

public partial class Audience
{
    [JsonProperty("user_id")]
    public List<string> UserId { get; set; }
}

or if you can use a class instead of dictionary

public partial class Data
{
    [JsonProperty("add")]
    public Add Add { get; set; }

    [JsonProperty("audience")]
    public Audience Audience { get; set; }
}
public partial class Add
{
    [JsonProperty("welcome_email")]
    public List<string> WelcomeEmail { get; set; }

    [JsonProperty("goodby_email")]
    public List<string> GoodbyEmail { get; set; }
}

CodePudding user response:

public class Add
{
    [JsonProperty("welcome_email")]
    public List<string> WelcomeEmail{ get; set; }
    [JsonProperty("goodby_email ")]
    public List<string> GoodbyEmail{ get; set; }
}

public class Audience
{
    [JsonProperty("user_id ")]
    public List<string> UserId { get; set; }
}

public class Root
{
    public Add Add { get; set; }
    public Audience Audience { get; set; }
}

Your models should be similar to this

  • Related