Android JSON对象创建

时间:2015-10-13 04:05:19

标签: java android

如何使用java代码在Android中创建JSON对象。

{
    "apikey": "example apikey",
    "id": "example id",
    "email": {
        "email": "example email",
        "euid": "example euid",
        "leid": "example leid"
            }
}

4 个答案:

答案 0 :(得分:2)

你可以创建你提到的json,如下所示:

 public void createJson() {
        try {
            // create outer json
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("apikey", "example api key");
            jsonObject.put("id", "example id");

            // create email json
            JSONObject emailJsonObject = new JSONObject();
            emailJsonObject.put("email", "email");
            emailJsonObject.put("euid", "euid");
            emailJsonObject.put("leid", "leid");

            // add email json to outer json
            jsonObject.put("email", emailJsonObject);

            System.out.println("-----printing json------" + jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

谢谢.. !!

答案 1 :(得分:1)

你可以这样做:

JSONObject jsonObject = new JSONObject();
jsonObject.put("apikey","example apikey");
jsonObject.put("id","example id");

JSONObject innerObject = new JSONObject();

innerObject.put("email","example email");
....
jsonObject.put("email",innerObject);

要转换为String,您可以执行jsonObject.toString();

答案 2 :(得分:1)

喜欢这个。

JSONObject myJson = new JSONObject();
myJson.put("apikey","example apikey");
myJson.put("id","example id");

JSONObject emailObject = new JSONObject();
emailObject.put("email","example email");
emailObject.put("euid","example euid");
emailObject.put("leid","example leid");

myJson.put("email",emailObject);

答案 3 :(得分:0)

使用您想要的构造函数创建一个类。 喜欢:

class MyJsonObj{
  public string apikey;
  public string id;
  public string[] email;
}

然后实例化

MyJsonObj myObj = new MyJsonObj();
myObj.apikey = "testKey";
myObj.id = "0123";
myObj.email = new string[]{"01@gamil.com","02@gmail.com"};

最后,通过Gson库转换为json字符串

Gson gson = new Gson();
String json = gson.toJson(myObj);