简体   繁体   English

如何为json数组中的每个子项添加父项?

[英]How to add a parent to every child in a json array?

I'm working on a Web Service in ASP.NET that has two methods, what I want to do is to return the data in JSON format, I'm usin JSON.NET library. 我正在使用两种方法在ASP.NET中的Web服务上工作,我想做的就是以JSON格式返回数据,而我使用的是JSON.NET库。

This is one of the methods: 这是方法之一:

[WebMethod]
    public string GetReservas()
    {
        var json = "";

        var data = from result in DCHotel.visHTLReservaciones select result;

        json = JsonConvert.SerializeObject(data);

        return json;          
    }

When I run the web service, this is the output in my browser: 当我运行Web服务时,这是浏览器中的输出:

[{"id":1,"name":"jose","age":22},{"id":2,"name":"john","age":21}] [{ “ID”:1, “名称”: “圣何塞”, “年龄”:22},{ “ID”:2 “名称”: “约翰”, “年龄”:21}]

And what I need is something like this: 我需要的是这样的:

["person":[{"id":1,"name":"jose","age":22}],"person":[{"id":2,"name":"john","age":21}]] [ “人”:[{ “ID”:1, “名称”: “圣何塞”, “年龄”:22}], “人”:[{ “ID”:2 “名称为”: “约翰”,”年龄“:21}]

I need to add parents to every child in the array, I don't know how to do it, and I searched a lot and can't find the solution to this, hope you can help me. 我需要为数组中的每个孩子添加父母,我不知道该怎么做,我进行了很多搜索,但找不到解决方案,希望您能对我有所帮助。

Thanks. 谢谢。

It's very easy, change your linq query to this: 非常简单,将您的linq查询更改为:

var data = from result in DCHotel.visHTLReservaciones select new { person =  result };

Instead of taking just the result you encapsulate it on an anonymous class. 与其仅获取结果,还不将其封装在一个匿名类上。

Cheers. 干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM