【问题标题】:How to set JSON Object Start with Result?.Net MySQL JSON Restful Webservice?如何设置 JSON 对象以结果开头?.Net MySQL JSON Restful Webservice?
【发布时间】:2014-05-26 09:45:45
【问题描述】:

我跟随 this 创建了 Restful Web 服务,将 JSON 显示为来自 MySQL 数据库的输出。

我成功完成了,但这里我在数据库中有近 100 个不同名称的表

为了获取数据,我正在使用这个:

ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle =    WebMessageBodyStyle.Wrapped, UriTemplate = "getAllCustomers")]
List<wsCustomer> GetAllCustomers();

还有这个:

public class Service1 : IService1
{
 public List<wsCustomer> GetAllCustomers()
{
NorthwindDataContext dc = new NorthwindDataContext();
List<wsCustomer> results = new List<wsCustomer>();

foreach (Customer cust in dc.Customers)
{
    results.Add(new wsCustomer() { 
        CustomerID = cust.CustomerID,
        CompanyName = cust.CompanyName,
        City = cust.City
    });
}

return results;
}

我得到这样的数据输出:

{
    "CustomerResult": [
        {
            "CustomerID ": "12124",
            "CompanyName ": "http://www.google.com",
            "City ": "xyz"
        }
    ]
}

但是这里的问题在于每个结果我得到的表名结果就像我有另一个表一样

{
    "UserResult": [
        {
            "UserID ": "12124",
            "CompanyName ": "http://www.google.com",
            "City ": "xyz"
        }
    ]
}

So Here Insted Of CustomerResultUserResult 我想要它作为 Result

有没有办法将其显示为所有表格的结果。

请给我建议..

【问题讨论】:

    标签: c# mysql json web-services rest


    【解决方案1】:

    您可以使用类似地图的结构来实现这一点。我不确定.Net,但在java中我们这样做:

        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("result","customerList");
        resultMap.put("status","success");
    

    您也可以使用地图。根据我的理解,在您的场景中,它返回表名作为键,因为您的方法直接返回列表。要使其成为 json,它需要一个密钥。

    【讨论】:

    • 谢谢先生,请您尝试告诉我关于这个 C#(.net)
    【解决方案2】:

    我在 JAVA 中尝试过使用 Map,

    public List<wsCustomer> GetAllCustomers()
                {
                    NorthwindDataContext dc = new NorthwindDataContext();
                    List<wsCustomer> results = new List<wsCustomer>();
    
                    foreach (Customer cust in dc.Customers)
                    {
                        results.Add(new wsCustomer() {
                            CustomerID = cust.CustomerID,
                            CompanyName = cust.CompanyName,
                            City = cust.City
                        });
                    }
                    Map<String,List<wsCustomer>> resultMap = new HashMap<String,List<wsCustomer>>();
                    resultMap.put("result",results);
                    return resultMap;
                }
    

    【讨论】:

    • 谢谢你,先生,你能告诉我关于这个 C#(.net)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 2016-12-23
    • 2011-02-13
    相关资源
    最近更新 更多