How to return JSon object

后端 未结 2 1890
我寻月下人不归
我寻月下人不归 2020-11-30 08:47

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\", val         


        
相关标签:
2条回答
  • 2020-11-30 09:17

    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"
        }
      ]
    }
    
    0 讨论(0)
  • 2020-11-30 09:18

    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"}]}
    
    0 讨论(0)
提交回复
热议问题