如何在JSON中添加根节点

时间:2016-06-03 10:06:49

标签: java json eclipse

我需要在我的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。提前谢谢。

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

你可以使用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
}

答案 2 :(得分:0)

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

        }
    }