28

I am using a jQuery plugin that need a JSON object with following structure(I will be retrieving the values from database):

{ results: [
    { id: "1", value: "ABC", info: "ABC" },
    { id: "2", value: "JKL", info: "JKL" },
    { id: "3", value: "XYZ", info: "XYZ" }
] }

Here is my class:

public class results
{
    int _id;
    string _value;
    string _info;

    public int id
    {
        get
        {
            return _id;
        }
        set
        {
            _id = value;
        }
    }
    public string value
    {
        get
        {
            return _value;
        }
        set
        {
            _value = value;
        }
    }
    public string info
    {
        get
        {
            return _info;
        }
        set
        {
            _info = value;
        }
    }
}

This is the way I serialize it:

results result = new results();
result.id = 1;
result.value = "ABC";
result.info = "ABC";
string json = JsonConvert.SerializeObject(result);

But this will return only one row. Can you please help me in returning more than one result? How can I get the result in the format specified above?

ShaneBlake
  • 11,056
  • 2
  • 26
  • 43
user1640256
  • 1,691
  • 7
  • 25
  • 48
  • 7
    Your `result` variable is a single item, not a collection. You need a collection if you want an array of items. – Oded May 08 '13 at 13:28
  • you can look this link http://stackoverflow.com/questions/6201529/turn-c-sharp-object-into-a-json-string-in-net-4/6201609#6201609 – nercan May 08 '13 at 13:32
  • 1
    http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializingCollections.htm –  May 08 '13 at 13:36
  • @nercan: That has nothing to do with his question.. he is using James Newton-King's plugin. –  May 08 '13 at 13:39

2 Answers2

37

First of all, there's no such thing as a JSON object. What you've got in your question is a JavaScript object literal (see here for a great discussion on the difference). Here's how you would go about serializing what you've got to JSON though:

I would use an anonymous type filled with your results type:

string json = JsonConvert.SerializeObject(new
{
    results = new List<Result>()
    {
        new Result { id = 1, value = "ABC", info = "ABC" },
        new Result { id = 2, value = "JKL", info = "JKL" }
    }
});

Also, note that the generated JSON has result items with ids of type Number instead of strings. I doubt this will be a problem, but it would be easy enough to change the type of id to string in the C#.

I'd also tweak your results type and get rid of the backing fields:

public class Result
{
    public int id { get ;set; }
    public string value { get; set; }
    public string info { get; set; }
}

Furthermore, classes conventionally are PascalCased and not camelCased.

Here's the generated JSON from the code above:

{
  "results": [
    {
      "id": 1,
      "value": "ABC",
      "info": "ABC"
    },
    {
      "id": 2,
      "value": "JKL",
      "info": "JKL"
    }
  ]
}
Community
  • 1
  • 1
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • 1
    I'd leave the IDs as `int` or whatever makes sense in code; Javascript can usually handle them just fine either way, so you might as well take advantage of strong typing while you can. There's always `.ToString()` if they need to be strings for transit. – anaximander May 08 '13 at 13:42
  • 1
    @anaximander: That is true. I'd prefer `int` personally as well. I'll change it back and make a note. Thanks for the feedback! – Andrew Whitaker May 08 '13 at 13:43
  • @AndrewWhitaker: The code you posted is just not compiling. It's giving errors as "Type expected", "; expected", "invalid expression term ','", "a new expression requires () or [] after type", and "invalid expression term ()" – user1640256 May 08 '13 at 14:40
  • @user1640256: What version of the .NET framework are you using? – Andrew Whitaker May 08 '13 at 14:43
6

You only have one row to serialize. Try something like this :

List<results> resultRows = new List<results>

resultRows.Add(new results{id = 1, value="ABC", info="ABC"});
resultRows.Add(new results{id = 2, value="XYZ", info="XYZ"});

string json = JavaScriptSerializer.Serialize(new { results = resultRows});
  • Edit to match OP's original json output

** Edit 2 : sorry, but I missed that he was using JSON.NET. Using the JavaScriptSerializer the above code produces this result :

{"results":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"XYZ","info":"XYZ"}]}
ShaneBlake
  • 11,056
  • 2
  • 26
  • 43