Lakshay Dulani
Lakshay Dulani

Reputation: 1775

How to build this json using .net C#?

I want to build a json like this:

...
  "conditions": [
      [
        "Language",
        "IN",
        [
          "en"
        ]
      ]
    ]
...

I am using this code:

new JProperty("conditions", new JArray(new JArray((new JArray("Language", "IN", new JArray(IsEnglish ? "en" : "es"))))))

But this one built me a json with one less array.

  "conditions": 
      [
        "Language",
        "IN",
        [
          "en"
        ]
      ]

I tried to nest this into another JArray but that is not working. Please suggest.

EDIT: This is the whole Json making statement

 JObject json = new JObject(
           new JProperty("application", pwApplication),
           new JProperty("auth", pwAuth),
           new JProperty("notifications",
               new JArray(
                   new JObject(
                       new JProperty("send_date", "now"),
                       new JProperty("content", new JObject(new JProperty("en", pushContentEnglish), new JProperty("es", pushContentSpanish))),
                       new JProperty("ios_badges", 0),
                       new JProperty("data", new JObject(new JProperty("custom", new JObject(new JProperty("t", notificationType), new JProperty("i", objectId))))),
                       new JProperty("devices", new JArray(strDeviceArray)),
                       new JProperty("conditions", new JArray(new JArray((new JArray("Language", "IN", new JArray(IsEnglish ? "en" : "es")))))
                       )))));

Upvotes: 0

Views: 207

Answers (3)

raj
raj

Reputation: 168

This seems to work:

new JProperty("conditions", new JArray((JContainer)new JArray("Language", "IN", new JArray(IsEnglish ? "en" : "es"))))

And the reason this works is because the JArray(JArray) constructor copies the elements from the JArray parameter to the JArray being constructed, whereas casting it to JContainer (from which JArray inherits) invokes the JArray(Object) overload.

Upvotes: 1

zaitsman
zaitsman

Reputation: 9499

If you're using Json.Net, why not do:

var conditions = new[] { new object[] { "Language", "IN", new[] { "en" } } };
var result = "conditions:" + JsonConvert.SerializeObject(conditions);

Upvotes: 1

Bruno Casali
Bruno Casali

Reputation: 1380

I think do you using only one data...

"conditions": [
  [
    "Language",
    "IN",
    [
      "en"
    ]
  ]
]

but if you try to make one more...

"conditions": [
    [
        "Language",
        "IN",
        [
            "en"
        ]
    ],
    [
        "Language",
        "IN",
        [
            "pt"
        ]
    ]
]

If you can test this code with more than one data in this expected array... ? You'll tried this?

Upvotes: 0

Related Questions