Reputation:
How to create a JSON object, in Android using java code.
{
"apikey": "example apikey",
"id": "example id",
"email": {
"email": "example email",
"euid": "example euid",
"leid": "example leid"
}
}
Upvotes: 1
Views: 109
Reputation: 2575
Do like thist.
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);
Upvotes: 1
Reputation: 11464
You can create json you mentioned in question as below :
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();
}
}
Thanks..!!
Upvotes: 2
Reputation: 1541
Create a class with the constructor you want. Likes:
class MyJsonObj{
public string apikey;
public string id;
public string[] email;
}
Then instance the class
MyJsonObj myObj = new MyJsonObj();
myObj.apikey = "testKey";
myObj.id = "0123";
myObj.email = new string[]{"[email protected]","[email protected]"};
Last, convert to json string by Gson library
Gson gson = new Gson();
String json = gson.toJson(myObj);
Upvotes: 0
Reputation: 3243
you can do like this:
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);
and to convert to String you can do like jsonObject.toString();
Upvotes: 1