I am having the following issue when trying to create some JSON in C#.
Below is my code for creating the JSON:
JObject data =
new JObject(
new JProperty("channel", "Test"),
new JProperty("terminal", "0"),
new JProperty("order",
new JArray(
new JObject(
new JProperty("orderId", txtSessionId.Text),
new JProperty("description", "test"),
new JProperty("currency", "EUR"),
new JProperty("totalAmount", txtPayAmount.Text),
new JProperty("customer",
new JArray(
new JObject(
new JProperty("name", "Test Name"),
new JProperty("phone", "00000000000"),
new JProperty("email", "test@test.com"))))))));
This produces this JSON which is incorrect:
{
"channel": "Test",
"terminal": "0",
"order": [
{
"orderId": "30",
"description": "test",
"currency": "EUR",
"totalAmount": "10",
"customer": [
{
"name": "Test Name",
"phone": "00000000000",
"email": "test@test.com"
}
]
}
]
}
I would like it to come out like this:
{
"channel":"Test",
"terminal":"0",
"order":[
{
"orderId":"30",
"description":"test",
"currency":"EUR",
"totalAmount":"10"
}
],
"customer":[
{
"name":"Test Name",
"phone":"00000000000",
"email":"test@test.com"
}
]
}
If anyone can point me in the right direction that would be great, thank you.
>Solution :
Fixing your indentation makes it obvious where you went wrong…
JObject data = new JObject(
new JProperty("channel", "Test"),
new JProperty("terminal", "0"),
new JProperty("order",
new JArray(
new JObject(
new JProperty("orderId", txtSessionId.Text),
new JProperty("description", "test"),
new JProperty("currency", "EUR"),
new JProperty("totalAmount", txtPayAmount.Text),
new JProperty("customer",
new JArray(
new JObject(
new JProperty("name", "Test Name"),
new JProperty("phone", "00000000000"),
new JProperty("email", "test@test.com")
)
)
)
)
)
)
);
As you can see, the customer object is inside the first object in the order array. Move some closing parentheses about should resolve it
JObject data = new JObject(
new JProperty("channel", "Test"),
new JProperty("terminal", "0"),
new JProperty("order",
new JArray(
new JObject(
new JProperty("orderId", txtSessionId.Text),
new JProperty("description", "test"),
new JProperty("currency", "EUR"),
new JProperty("totalAmount", txtPayAmount.Text),
)
)
),
new JProperty("customer",
new JArray(
new JObject(
new JProperty("name", "Test Name"),
new JProperty("phone", "00000000000"),
new JProperty("email", "test@test.com")
)
)
)
);