Ok, so I am trying to send POST commands over an http connection, and using JSON formatting to do so. I am writing the program to do this in C#, and was wondering how I would format an array of values to be passed as JSON to the server.
Currently I have this:
new {name = "command" , index = "X", optional = "0"}
Which translates to this in JSON:
"name": "command", "index": "X", "optional": "0"
And I want to make an array, called items, where each element contains these three values. So it would essentially be an array of objects, in which the object contains a name, an index, and an optional field.
My guess was that it would be something along the lines of this:
new {items = [(name = "command" , index = "X", optional = "0"), (name = "status" , index = "X", optional = "0")]}
Which, if it were correct syntax, would translate to this in JSON:
"items": [ { "name": "command", "index": "X", "optional": "0" }, { "name": "status", "index": "X", "optional": "0" } ]
But, evidently I'm doing it wrong. Ideas? Any help is appreciated.
A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.
JSON can be either an array or an object.
' { } ' used for Object and ' [] ' is used for Array in json.
JSONArray pdoInformation = new JSONArray(); JSONObject pDetail1 = new JSONObject(); JSONObject pDetail2 = new JSONObject(); JSONObject pDetail3 = new JSONObject(); pDetail1. put("productid", 1); pDetail1. put("qty", 3); pDetail1. put("listprice", 9500); pDetail2.
You're close. This should do the trick:
new {items = new [] { new {name = "command" , index = "X", optional = "0"}, new {name = "command" , index = "X", optional = "0"} }}
If your source was an enumerable of some sort, you might want to do this:
new {items = source.Select(item => new { name = item.Name, index = item.Index, options = item.Optional })};
You'd better create some class for each item instead of using anonymous objects. And in object you're serializing you should have array of those items. E.g.:
public class Item { public string name { get; set; } public string index { get; set; } public string optional { get; set; } } public class RootObject { public List<Item> items { get; set; } }
Usage:
var objectToSerialize = new RootObject(); objectToSerialize.items = new List<Item> { new Item { name = "test1", index = "index1" }, new Item { name = "test2", index = "index2" } };
And in the result you won't have to change things several times if you need to change data-structure.
p.s. Here's very nice tool for complex json
s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With