如何在 JSON 中添加根节点



我需要在我的 JSON 响应中包含顶部节点。我在 REST Web 服务中的 JSON 响应:

[
    {
        "address": "delhi",
        "fristname": "xxxx",
        "id": 1,
        "lastname": "xxxx",
        "phone": "0000000"
    },
    {
        "address": "ssss",
        "fristname": "yyyy",
        "id": 2,
        "lastname": "yyyyy",
        "phone": "0000000"
    },
    {
        "address": "wwww",
        "fristname": "aaaa",
        "id": 3,
        "lastname": "aaaaa",
        "phone": "0000000"
    }
]

我想要这样的 JSON 响应:

"employee": [
    {
        "address": "delhi",
        "fristname": "xxxx",
        "id": 1,
        "lastname": "xxxx",
        "phone": "0000000"
    },
    {
        "address": "ssss",
        "fristname": "yyyy",
        "id": 2,
        "lastname": "yyyyy",
        "phone": "0000000"
    },
    {
        "address": "wwww",
        "fristname": "aaaa",
        "id": 3,
        "lastname": "aaaaa",
        "phone": "0000000"
    }
]

请告诉我如何添加根节点 JSON。提前谢谢。

你可以在 Java 中这样做。创建一个新的 JSON 对象并将数组放入其中。

JSONObject myobj = new JSONObject(); 
myobj.put("employees", <your_json_array>);

你可以使用 Jackson 注释 JsonRootName:

类似于 XmlRootElement 的注释,用于指示要用于的名称 根级包装(如果已启用包装)。注释本身确实如此 不表示应使用包装;但如果是,名称用于 序列化应在此处指定名称,反序列化程序将 期待这个名字。

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);

并按如下方式注释您的类:

@JsonRootName(value = "employee")
public static class Employee {
  private String address;
  private String firstName;
  // more... with getters and setters
}
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
  public class Employee
    {
        public string address { get; set; }
        public int phone { get; set; }
    }
    public partial class Samplepage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            List<Employee> eList = new List<Employee>();
            Employee employee = new Employee();
            employee.address = "Minal";
            employee.phone = 24;
            eList.Add(employee);
            employee = new Employee();
            employee.address = "Santosh";
            employee.phone = 24;
            eList.Add(employee);
            string ans = JsonConvert.SerializeObject(eList, Formatting.Indented);

            JArray a = JArray.Parse(ans);
            JObject UpdateAccProfile = new JObject(
                               new JProperty("employee", a)
                               );
        }
    }

最新更新