如何返回 JSON 对象

时间:2023-04-26
本文介绍了如何返回 JSON 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在使用一个 jQuery 插件,它需要一个具有以下结构的 JSON 对象(我将从数据库中检索值):

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" }
] }

这是我的课:

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;
        }
    }
}

这是我序列化的方式:

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?

推荐答案

首先,有 没有 JSON 对象之类的东西.您的问题是 JavaScript 对象文字(请参阅 这里 对差异进行了很好的讨论).以下是您将如何将您拥有的内容序列化为 JSON 的方法:

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:

我会使用一个匿名类型填充你的 results 类型:

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" }
    }
});

另外,请注意,生成的 JSON 的结果项的 id 类型为 Number,而不是字符串.我怀疑这会是一个问题,但是在 C# 中将 id 的类型更改为 string 很容易.

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#.

我还会调整您的 results 类型并去掉支持字段:

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; }
}

此外,类通常是 PascalCased 而不是 camelCased.

Furthermore, classes conventionally are PascalCased and not camelCased.

这是从上面的代码生成的 JSON:

Here's the generated JSON from the code above:

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

这篇关于如何返回 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:JSON.NET 反序列化特定属性 下一篇:如何在 JObject 中添加或更新 JProperty 值

相关文章