74

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.

3
  • C# does not have JSON literals. You need to use anonymous types. Commented Jun 3, 2013 at 14:09
  • 2
    Thats what I'm doing. hence, the new Commented Jun 3, 2013 at 14:10
  • And if you want to provide JSON serizalization, take a look: stackoverflow.com/questions/13278459/…. Commented Jun 3, 2013 at 14:11

4 Answers 4

114

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
})};
Sign up to request clarification or add additional context in comments.

3 Comments

@Dave what about if you need to do it dynamically. Like inside of a for loop ?
Well if you're in a for loop then you're going to have to create a real model instead of using anonymous types. If you can use LINQ (and I would prefer if you do) then you can simply "project" your results into an anonymous model like in my example.
I updated my answer to add an example of what you can do with an enumerable source.
48

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 jsons

1 Comment

If you have ASP.NET and Web Tools 2012 you also have this awesome Paste JSON as classes feature :)
12

Also , with Anonymous types ( I prefer not to do this) -- this is just another approach.

void Main()
{
    var x = new
    {
        items = new[]
        {
            new
            {
                name = "command", index = "X", optional = "0"
            },
            new
            {
                name = "command", index = "X", optional = "0"
            }
        }
    };
    JavaScriptSerializer js = new JavaScriptSerializer(); //system.web.extension assembly....
    Console.WriteLine(js.Serialize(x));
}

result :

{"items":[{"name":"command","index":"X","optional":"0"},{"name":"command","index":"X","optional":"0"}]}

Comments

-6
new {var_data[counter] =new [] { 
                new{  "S NO":  "+ obj_Data_Row["F_ID_ITEM_MASTER"].ToString() +","PART NAME": " + obj_Data_Row["F_PART_NAME"].ToString() + ","PART ID": " + obj_Data_Row["F_PART_ID"].ToString() + ","PART CODE":" + obj_Data_Row["F_PART_CODE"].ToString() + ", "CIENT PART ID": " + obj_Data_Row["F_ID_CLIENT"].ToString() + ","TYPES":" + obj_Data_Row["F_TYPE"].ToString() + ","UOM":" + obj_Data_Row["F_UOM"].ToString() + ","SPECIFICATION":" + obj_Data_Row["F_SPECIFICATION"].ToString() + ","MODEL":" + obj_Data_Row["F_MODEL"].ToString() + ","LOCATION":" + obj_Data_Row["F_LOCATION"].ToString() + ","STD WEIGHT":" + obj_Data_Row["F_STD_WEIGHT"].ToString() + ","THICKNESS":" + obj_Data_Row["F_THICKNESS"].ToString() + ","WIDTH":" + obj_Data_Row["F_WIDTH"].ToString() + ","HEIGHT":" + obj_Data_Row["F_HEIGHT"].ToString() + ","STUFF QUALITY":" + obj_Data_Row["F_STUFF_QTY"].ToString() + ","FREIGHT":" + obj_Data_Row["F_FREIGHT"].ToString() + ","THRESHOLD FG":" + obj_Data_Row["F_THRESHOLD_FG"].ToString() + ","THRESHOLD CL STOCK":" + obj_Data_Row["F_THRESHOLD_CL_STOCK"].ToString() + ","DESCRIPTION":" + obj_Data_Row["F_DESCRIPTION"].ToString() + "}
        }
    };

1 Comment

Could you explain how this does answer the question?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.