如何创建使用Java的JSONObject的正确JsonArray [英] How to create correct JsonArray in Java using JSONObject

查看:337
本文介绍了如何创建使用Java的JSONObject的正确JsonArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能创建一个使用JSONObject的JSON对象类似以下,在Java中?

how can I create a JSON Object like the following, in Java using JSONObject ?

{
 "employees": [
 { "firstName":"John" , "lastName":"Doe" }, 
 { "firstName":"Anna" , "lastName":"Smith" }, 
 { "firstName":"Peter" , "lastName":"Jones" } 
 ],
 "manager": [
 { "firstName":"John" , "lastName":"Doe" }, 
 { "firstName":"Anna" , "lastName":"Smith" }, 
 { "firstName":"Peter" , "lastName":"Jones" } 
 ]
 }

我已经找到了很多的例子,但不是我的确切JSONArray字符串。

I've found a lot of example, but not my exactly JSONArray string.

谢谢大家提前!

推荐答案

下面是一个使用Java 6中,让你开始有些code:

Here is some code using java 6 to get you started:

JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");

JSONArray ja = new JSONArray();
ja.put(jo);

JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);

编辑:由于出现了很多混乱关于 VS 添加在这里我将试图解释的差异。 Java 6中 org.json.JSONArray 包含方法,并在Java 7 javax.json 包含添加方法。

Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.

使用生成器模式在Java 7中这样的例子看起来是这样的:

An example of this using the builder pattern in java 7 looks something like this:

JsonObject jo = Json.createObjectBuilder()
  .add("employees", Json.createArrayBuilder()
    .add(Json.createObjectBuilder()
      .add("firstName", "John")
      .add("lastName", "Doe")))
  .build();

这篇关于如何创建使用Java的JSONObject的正确JsonArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆