How to write JSON object in java code? - java

My Json are following
{
"q": {
"region": "NYC",
"or": [
{
"duration": "12"
}
]
},
"sort": "recent"
}
How to write in JsonObject.I tried with following code:
JSONObject obj = new JSONObject();
JSONObject obj1 = new JSONObject();
JSONObject obj2 = new JSONObject();
JSONObject obj4 = new JSONObject();
try {
obj.put("q", obj1);
obj.put("sort", "recent");
obj1.put("reg", "NYC");
obj2.put("duration", new Integer(12));
obj4.put()
} catch (JSONException e) {
}
I got stuck in creating Array of list. How can I convert into Json Object?

You may build the JSONObject in this way:
public class Test {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("q", new JSONObject()
.put("region", "NYC")
.put("or", new JSONArray()
.put(new JSONObject()
.put("duration","12"))))
.put("sort", "recent");
System.out.println(obj);
}
}
The output:
{"q":{"or":[{"duration":"12"}],"region":"NYC"},"sort":"recent"}

Related

How to create a nested JSONObject [duplicate]

This question already has answers here:
Creating nested JSON object for the following structure in Java using JSONObject? [closed]
(2 answers)
Closed 2 years ago.
Below is my code. I still need to add the "studentInfo" field.
JSONObject jo = new JSONObject();
jo.put("name", "ALEX JAMES");
jo.put("id", "22284666");
jo.put("age","13")
JSON body message to be created:
{
"body": {
"studentInfo": {
"name": "ALEX JAMES",
"id": "22284666",
"age": "13"
}
}
}
you can nest objects
JSONObject studentInfo = new JSONObject();
studentInfo.put("name", "ALEX JAMES");
studentInfo.put("id", "22284666");
studentInfo.put("age","13");
JSONObject body = new JSONObject();
body.put("studentInfo" , studentInfo);
JSONObject wrapper = new JSONObject();
wrapper.put("body" , body);
This standalone example seems to do what you want:
import org.json.JSONObject;
class Main {
public static void main(String[] args) {
JSONObject jo = new JSONObject();
JSONObject body = new JSONObject();
jo.put("body", body);
JSONObject si = new JSONObject();
body.put("studentInfo", si);
si.put("name", "Alex James");
si.put("id", "22284666");
si.put("age", 13);
System.out.println(jo.toString(4));
}
}
Output
{"body": {"studentInfo": {
"name": "Alex James",
"id": "22284666",
"age": 13
}}}
Test it on repl.it.

How to create a JSONObject for nested json

I am unable to create a json object for nested json.
I can create json objects for basic json.
I am unable to add further fields.
final JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", "new name");
jsonObject.put("description", "new election");
} catch (JSONException e) {
e.printStackTrace();
}
Here is my json:
{
"name": "string",
"description": "string",
"candidates": [
"string"
],
"ballotVisibility": "string",
"voterListVisibility": true,
"startingDate": "2019-07-05T20:09:23.311Z",
"endingDate": "2019-07-05T20:09:23.311Z",
"isInvite": true,
"isRealTime": true,
"votingAlgo": "string",
"noVacancies": 0,
"ballot": [
{
"voteBallot": "string",
"voterEmail": "string"
}
]
}
You just need to create a new JSONObject then append it to the parent object with its new name. An example is shown below appending the ballot:
JSONObject jsonObject = new JSONObject();
JSONObject ballot = new JSONObject();
ballot.put("voteBallot","string");
ballot.put("voterEmail","string");
jsonObject.put("name", "new name");
jsonObject.put("description", "new election");
jsonObject.put("ballot", ballot); //Append the other JSONObject to the parent one
System.out.println(jsonObject.toString());
Output(with some formatting):
{
"ballot":
{
"voteBallot":"string",
"voterEmail":"string"
},
"name":"new name",
"description":"new election"
}
You can also use JSONArray instead and append it in the same manner.
Try this:
final JSONObject jsonObject = new JSONObject();
Map<String, String> map = new HashMap<>();
map.put("voteBallot", "string");
map.put("voterEmail", "string");
try {
jsonObject.put("name", "new name");
jsonObject.put("description", "new election");
jsonObject.put("candidates", new String[] {"new String"});
jsonObject.put("ballotVisibility", "string");
jsonObject.put("voterListVisibility", true);
jsonObject.put("startingDate", LocalDateTime.now().atZone(ZoneOffset.UTC));
jsonObject.put("ballot", new Map[]{map});
System.out.println("jsonObject = " + jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
it's not all the fields but it's all the different types hope it helps.
Output:
{
"ballot":[
{
"voteBallot":"string",
"voterEmail":"string"
}
],
"candidates":[
"new String"
],
"ballotVisibility":"string",
"name":"new name",
"voterListVisibility":true,
"description":"new election",
"startingDate":"2019-07-05T22:34:58.750Z"
}

Giving Name (Heading) to Objects in JsonArray

I want to send following data to server. It contains JsonArray of JsonObjects as shown below.
{
"users":[
{"user-1":{
"Name":"Amit",
"Age":"32",
"Gender":"male",
"Hobby":"Cricket"
}
"user-2":{
"Name":"Subodh",
"Age":"30",
"Gender":"male",
"Hobby":"Chess"
}
"user-3":{
"Name":"Mala",
"Age":"27",
"Gender":"female",
"Hobby":"Singing"
}
}
]
}
This is how I wrote json code for the same.
JSONObject userObject = new JSONObject();
JSONArray userArray = new JSONArray();
JSONObject user1 = new JSONObject();
try {
user1.put("Name", "Amit");
user1.put("Age", "32");
user1.put("Gender", "Male");
user1.put("Hobby", "Cricket");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject user2 = new JSONObject();
try {
user2.put("Name", "Subodh");
user2.put("Age", "30");
user2.put("Gender", "Male");
user2.put("Hobby", "Chess");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject user3 = new JSONObject();
try {
user3.put("Name", "Mala");
user3.put("Age", "27");
user3.put("Gender", "Female");
user3.put("Hobby", "Singing");
} catch (JSONException e) {
e.printStackTrace();
}
userArray.put(user1);
userArray.put(user2);
userArray.put(user3);
try {
userObject.put("user", userArray);
} catch (JSONException e) {
e.printStackTrace();
}
However I am not able to figure out how to give name to Objects (user-1, user-2 etc.) in the JsonArray. Can someone help to do that. I want to give Heading to each JsonObject in the JsonArray.
Your JSON is invalid.
Elements in JSON arrays don't have keys ("headings", as you call them). Only values in JSON objects have keys.
So, this is wrong:
{
"users": [
"user-1": {
"Name": "Amit",
"Age": "32",
"Gender": "male",
"Hobby": "Cricket"
}
]
}
While this is correct:
{
"users": {
"user-1": {
"Name": "Amit",
"Age": "32",
"Gender": "male",
"Hobby": "Cricket"
}
}
}
To get the correct JSON, simply use a JSONObject instead of a JSONArray:
JSONObject resultObject = new JSONObject();
JSONObject usersObject = new JSONObject();
JSONObject user1 = new JSONObject();
user1.put("Name", "Amit");
user1.put("Age", "32");
user1.put("Gender", "Male");
user1.put("Hobby", "Cricket");
usersObject.put("user-1", user1);
// repeat for user 2, 3, 4, ...
resultObject.put("users", usersObject);
Write the JSON object name like below code in every JSONObject creation :-
JSONObject jsonobj = new JSONObject("user1 ");
try {
jsonobj.put("Name", "Amit");
jsonobj.put("Age", "32");
jsonobj.put("Gender", "Male");
jsonobj.put("Hobby", "Cricket");
} catch (JSONException e) {
e.printStackTrace();
}

How to parse this type of JSON in Java?

How do I fetch the third leaveTypeId and year from leaveInfo?
{
"statusCode":"1001",
"message":"Success",
"response":{
"leaveInfo":[
{
"leaveTypeId":1,
"year":2014
},
{
"leaveTypeId":2,
"year":2014
},
{
"leaveTypeId":3,
"year":2014,
},
{
"leaveTypeId":4,
"year":2014
},
{
"leaveTypeId":5,
"year":2014
},
{
"leaveTypeId":6,
"year":2014
}
]
}
}
I did this to achieve my need
JSONObject jobj1 = new JSONObject(result);
String statusCode = jobj1.getString("statusCode");
if (statusCode.equalsIgnoreCase("1001"))
{
String response = jobj1.getString("response");
JSONObject jobj2 = new JSONObject(response);
String leaveInfo = jobj2.getString("leaveInfo");
System.out.println("leaveInfo: "+leaveInfo);
}
I don't know how to go further as there are no key values for the arrays inside leaveInfo. Please help me in this regard.
Use this
JSONObject jobj1 = new JSONObject(result);
String statusCode = jobj1.getString("statusCode");
if (statusCode.equalsIgnoreCase("1001"))
{
String response = jobj1.getString("response");
JSONObject jobj2 = new JSONObject(response);
JSONArray ary=jobj2.getJSONArray("leaveInfo");
for(int i=0;i<ary.length;i++){
JSONObject obj=ary.getJSONObject(i);
String leaveInfo=obj.getString("leaveTypeId");
System.out.println("leaveInfo: "+leaveInfo);
}
}
I hope this will help to you :)

Ending up creating wrong JSON

I need to produce this JSON Object
{
"Soft Drinks": {
"T2": [
{
"name": "Bottled",
"T3": [
{
"name": "Lemon",
"T4": [
{
"leaf": [
{
"name": "500 ML"
}
]
}
]
}
]
}
]
}
}
But i am always ending up with creatint this JSON
{
"Soft Drinks": {
"T2": [
{
"name": "Bottled",
"T3": [
{
"name": "Lemon",
"leaf": [
{
"name": "500 ML"
}
]
}
]
}
]
}
}
The leaf level object should come under different obect that is T4
This is my program
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class BuildJSOn {
public static void main(String[] args) throws JSONException {
JSONObject leaf = new JSONObject().put("name", "500 ML");
JSONObject lemon = new JSONObject().put("name", "Lemon").put("leaf", new JSONArray().put(leaf));
JSONArray t3Array = new JSONArray().put(lemon);
JSONObject bottled = new JSONObject().put("name", "Bottled").put("T3", t3Array);
JSONObject softDrink = new JSONObject().put("T2", new JSONArray().put(bottled));
JSONObject json = new JSONObject().put("Soft Drinks", softDrink);
System.out.println(json);
}
}
Try this:
JSONArray t4Array= new JSONArray();
JSONArray leaf= new JSONArray();
JSONObject newLeaf = new JSONObject().put("name", "500 ML");
leaf.put(newLeaf);
JSONObject t4Obj= new JSONObject().put("leaf",leaf);
t4Array.put(t4Obj);
JSONObject lemon = new JSONObject().put("name", "Lemon").put("T4", t4Array);
JSONArray t3Array = new JSONArray().put(lemon);
JSONObject bottled = new JSONObject().put("name", "Bottled").put("T3", t3Array);
JSONObject softDrink = new JSONObject().put("T2", new JSONArray().put(bottled));
JSONObject json = new JSONObject().put("Soft Drinks", softDrink);
Hope it helps.
According to the JSON structure you require, this is how your code should look.
JSONObject lemon = new JSONObject().put("name", "Lemon");
JSONArray t4 = new JSONArray().put(new JSONObject().put("leaf", new JSONArray().put(leaf)));
lemon.put("T4", t4);
You don't seem to mention T4 anywhere. You don't state what library you're using, or how the library you're using works (I assume you didn't write it yourself if you don't know how to add arrays to it) but I'd guess you need something like you did when adding the earlier arrays:
JSONArray t3Array = new JSONArray().put(lemon).put("T4", new JSONArray().put(leaf));
This doesn't really feel like a particularity nice solution, and that data structure looks a bit bizarre, but you need to add a JSONArray T4 somewhere!

Categories

Resources