Multiple values for a JSON key - java

I am a beginner on JSON in Java http://json.org/java/
How can I create a JSON object like this?
{
"RECORD": {
"customer_name": "ABC",
"customer_type": "music"
}
}

Try like this:
JSONObject jsonObject = new JSONObject();
jsonObject.put("customer_name", "ABC");
jsonObject.put("customer_type", "music");
JSONObject jsonObject_rec = new JSONObject();
jsonObject_rec.put("RECORD", jsonObject);
System.out.println(jsonObject_rec);

You have to make "RECORD" an JSONobject. This is an example:
JSONObject json = new JSONObject();
// Add a JSON Object
JSONObject Record = new JSONObject();
Record.put( "customer_name", "ABC");
Record.put( "customer_type", "music");
json.put( "RECORD", Record);
// P toString()
System.out.println( "JSON: " + json.toString() );

Related

JSON Input for POST request to call REST API

How do i convert a model Person to match the input?
Person p = new Person(name, age, amountInBank);
(name in String, age in int and amountInBank in double)
I want my JSON Input to be as follow:
{
"ID": "H123",
"list" : [
{
"name" : "ally",
"age": 18,
"amountInBank": 200.55
}
]
}
Currently my code to call REST API is:
JSONObject jsonInput= new JSONObject();
jsonInput.put("ID", "H123");
//put in list input in JSON -> HELP NEEDED
Resource resource = client.resource(URL HERE);
resource.contentType(MediaType.APPLICATION_JSON);
resource.accept(MediaType.APPLICATION_JSON);
ClientResponse cliResponse = resource.post(jsonInput);
Tried many ways but couldn't achieve the expected input for list in JSON format. Please help
Method 1:
ArrayList<Map<String, Object>> list = new ArrayList<>();
list.add(p);
jsonInput.put("list" , list);
Method 2:
JSONArray jsonArr = new JSONArray();
jsonArr.add(p);
jsonInput.put("list", jsonArr);
Method 3:
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "ally");
map.put("age", 18);
map.put("amountInBank" : 255.55);
jsonInput.put("list", map);
Safest bet is to use a well known library for the marshalling, such as Jackson. It is able to convert your object to JSON format with the following:
ObjectMapper mapper = new ObjectMapper(); //from Jackson library
Person p = new Person(name, age, amountInBank); //your POJO
String jsonString = mapper.writeValueAsString(p); //convert
Source: https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
There are also other alternatives, this is just a personal preference as Jackson is very widely used and well documented.
If you're trying to get a list of array JSON objects then just substitute the Person object with List<Person> and try to marshall that.
Try the code below
val listJsonArry = JsonArray()
var jsonObject = JsonObject()
jsonObject.add("name", "ally")
jsonObject.add("age", "18")
jsonObject.add("amountInBank", "200.55")
listJsonArry.add(jsonObject)
PostData
var postjsonObject = JsonObject()
postjsonObject.add("ID", "H123")
postjsonObject.add("list", listJsonArry)
First you have to create JSONObject and put ID, H123.
Then you have to create Another JSONObject wich will accept a person details.
pass another JSONObject to JSONArray and path JSONArray to JSONObjct. check the code
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject(); // first json object
jsonObject.put("ID", "H123"); put ids.
JSONArray jsonArray = new JSONArray(); // prepear json array
Person person = new Person("Ally", 18, 200.55); // create person object and populate it with data
// JSONObject jsonObject = new JSONObject(person); you can pass your person directly to JSONObject constructor and it will deparse it base on your getter methods in person class.
JSONObject jsonObject1 = new JSONObject(); // then pass person data to Json object
jsonObject1.put("name", person.getName());
jsonObject1.put("age", person.getAge());
jsonObject1.put("amountInBank", person.getAmountInBank());
jsonArray.put(jsonObject1); // pass json object to json array
jsonObject.put("list", jsonArray); // and pass json array to json object
System.out.println();
try (FileWriter file = new FileWriter("person.json")) {
file.write(jsonObject.toString(5));
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
above code will produce output
{
"ID": "H123",
"list": [{
"name": "Ally",
"amountInBank": 200.55,
"age": 18
}]
}
if you need to do that from database, more like there will be a lot of persons. put person object and json object in some kind of loop and populate it as long as you want. then pass it to json array and json array to jsonobject to have many records.

How to combine two or more JSON objects into one JSONObject

I've two JSON Objects as below
firstJSON: {"200":"success"}
secondJSON: {"401":"not found"}
I need to combine them as {"codes":{"200":"success"},{"401":"not found"}} using java.
I tried in 3 ways but couldn't achieve the desired output. Could you please help with code snippet?
code which I've tried as below
JSONObject firstJSON = new JSONObject();
firstJSON.put("200", "success");
String firstJSONStr = firstJSON.toString();
System.out.println("firstJSONStr--> " + firstJSONStr);
JSONObject secondJSON = new JSONObject();
secondJSON.put("401", "not found");
String secondJSONStr = secondJSON.toString();
System.out.println("secondJSONStr--> "+secondJSONStr);
String finalJSONStr = firstJSONStr + "," + secondJSONStr;
JSONObject finalJSON1 = new JSONObject();
finalJSON1.put("codes", new JSONObject(finalJSONStr));
System.out.println("finalJSON1--> " + finalJSON1.toString());
JSONObject finalJSON2 = new JSONObject();
finalJSON2.put("codes", finalJSONStr);
System.out.println("finalJSON2--> " + finalJSON2.toString());
JSONObject finalJSON3 = new JSONObject();
ArrayList<JSONObject> jsonArray = new ArrayList<JSONObject>();
jsonArray.add(firstJSON);
jsonArray.add(secondJSON);
finalJSON3.put("codes", jsonArray);
System.out.println("finalJSON3--> " + finalJSON3.toString());
Output:
firstJSONStr--> {"200":"success"}
secondJSONStr--> {"401":"not found"}
finalJSON1--> {"codes":{"200":"success"}}
finalJSON2--> {"codes":"{\"200\":\"success\"},{\"401\":\"not found\"}"}
finalJSON3--> {"codes":[{"200":"success"},{"401":"not found"}]}
Your expected JSON {"codes":{"200":"success"},{"401":"not found"}} is invalid. You can verify it with https://jsonlint.com/ which will produce an error:
Error: Parse error on line 4:
...00": "success" }, { "401": "not foun
---------------------^
Expecting 'STRING', got '{'
You most likely want an array to group the first and second object which results in below JSON (do notice the square brackets [ and ]):
{"codes":[{"200":"success"},{"401":"not found"}]}
This can be achieved with:
JSONObject first = new JSONObject();
first.put("200", "success");
JSONObject second = new JSONObject();
second.put("401", "not found");
JSONArray codes = new JSONArray();
codes.put(first);
codes.put(second);
JSONObject root = new JSONObject();
root.put("codes", codes);
System.out.println(root);
Got the logic finally.
JSONObject successJSON = new JSONObject();
successJSON.put("description", "success");
JSONObject scJSON = new JSONObject();
scJSON.put("200", successJSON);
JSONObject failJSON = new JSONObject();
failJSON.put("description","failure");
scJSON.put("401", failJSON);
JSONObject finalJSON = new JSONObject();
finalJSON.put("codes", scJSON);
System.out.println("finalJSON --> "+finalJSON.toString());

creating nested JSON object in Java and passing it as request using RestPost method?

I want to build a JSON Object similar to the following structure in java, and then pass it as a request using the restPost method.
{
"fields": [
{
"SESSION_SESSIONNUMID": "500"
},
{
"SESSION_STATUS": "BP"
},
{
"SESSION_DESCRIPTION": "Updated"
},
{
"SESSION_SESSIONDATE": "2016-07-20"
},
{
"SESSION_CURRENCY_TYPE": "USD"
}
]
}
So this is what I did ,
public void Insert() {
try {
String lstrPath = Constants.MIP_BASE_URI + "/api/te/JV/sessions";
System.out.println("Path for creation of session :\n " + lstrPath);
//create the JSON object containing the new contacts details.
JSONObject array = new JSONObject();
JSONObject object = new JSONObject();
JSONObject A1 = new JSONObject();
A1.put("SESSION_SESSIONNUMID " , "100 ");
JSONObject A2 = new JSONObject();
A2.put("SESSION_STATUS " , "BP");
JSONObject A3 = new JSONObject();
A3.put("SESSION_DESCRIPTION " , "CODING");
JSONObject A4 = new JSONObject();
A4.put("SESSION_SESSIONDATE" , "2016-10-20");
JSONObject A5 = new JSONObject();
A5.put("SESSION_CURRENCY_TYPE" , "USD");
object.put("def", array);
System.out.println("Passing request :\n" + A1.toString(1));
JSONObject ljsonResponse = RestCalls.RestPost(lstrPath,
A1, Constants.REQUESTING_CLASS.MIP);
if (ljsonResponse != null) {
Constants.MIP_TOKEN = ljsonResponse.getString("token");
}
System.out.println("Token from response: " + Constants.MIP_TOKEN);
Constants.MIP_AUTH_HEADER = new BasicHeader("Authorization-Token",
Constants.MIP_TOKEN);
} catch (JSONException ex) {
Logger.getLogger(ConnectToMip.class.getName()).log(Level.SEVERE, null,ex);
}
}
And now the issue is that In the above code I am able to create multiple JSON Objects required to create a session , but now I am unable to figure out how do I send(pass) multiple JSON objects in the response.
Note : In the last line of code below, I send 1 JSON Object(A1) as a response, similarly I need to send multiple JSON Objects that I created (A2, A3 , A4 , A5) in the response for a successful POST .
First I convert my complex json into java like this,
JSONArray json = new JSONArray();
JSONObject Final = new JSONObject();
JSONObject A1 = new JSONObject();
A1.put("SESSION_SESSIONNUMID" , "212");
JSONObject A2 = new JSONObject();
A2.put("SESSION_STATUS" , "BP");
JSONObject A3 = new JSONObject();
A3.put("SESSION_DESCRIPTION" , "CODING");
JSONObject A4 = new JSONObject();
A4.put("SESSION_SESSIONDATE" , "2016-10-20");
JSONObject A5 = new JSONObject();
A5.put("SESSION_CURRENCY_TYPE" , "USD");
json.put(A1);
json.put(A2);
json.put(A3);
json.put(A4);
json.put(A5);
Final.put("fields",json);
and then I pass Final into my tostring.

Add List<String> to the JSONArray

I am trying to greate JSON with the JSON library. At the momant I am creating JSONArray to add to add all the value in my List to it but I am facing this Problem
he method put(int, boolean) in the type JSONArray is not applicable for the arguments (String, List)
at this line arrivalMoFr.put("mon-fri", timeEntries); How can I add List to the JSONArray?
I appreciate any help.
Code:
List<String> timeEntries = entry.getValue();
try {
JSONObject timeTable = new JSONObject();
timeTable.put("route", route);
JSONObject info = new JSONObject();
info.put("direction", direction);
JSONObject stops = new JSONObject();
stops.put("stops_name", key);
JSONObject arrivals = new JSONObject();
JSONArray arrivalMoFr = new JSONArray();
//The error is here.
arrivalMoFr.put("mon-fri", timeEntries);
arrivals.put("mon-fri", arrivalMoFr);
stops.put("arrival_time", arrivals);
info.put("stops", stops);
timeTable.put("info", info);
System.out.println(timeTable.toString(3));
}
Edit:
I added it like this but I am getting now this result:
JSONObject arrivals = new JSONObject();
JSONArray arrivalMoFr = new JSONArray();
arrivalMoFr.put( timeEntries);
arrivals.put("mon-fri", arrivalMoFr);
Result:
{
"route": "4",
"info": {
"stops": {
"arrival_time": {"mon-fri": [[
"05:04",
"18:41",
"19:11",
"19:41",
"20:11"
]]},
"stops_name": "Heiweg "
},
"direction": "Groß Grönau"
}
}
JSONArray att = new JSONArray(YourList);
You can use Gson to convert List<String> to JSON
List<String> listStrings = new ArrayList<String>();
listStrings.add("a");
listStrings.add("b");
Gson objGson = new Gson();
System.out.println(objGson.toJson(listStrings));
Output
["a","b"]

Android: How to get certain values from JSON

I have the following code in my main activity.
JSONObject jObj = new JSONObject(loadJSONFromAsset());
jObj.getJSONObject("body");
The contents of jObj looks like this:
{
"body" : {
"name" : {
"test" : "abc"
}
}
}
I can get the value of "body" by iterating "jObj.keys()", but how can I get the value of "name"?
Use this:
JSONObject jObj = new JSONObject(loadJSONFromAsset());
JSONObject objectName = jObj.getJSONObject("body").getJSONObject("name");
String test = objectName.getString("test"); //return abc
Try this..
JSONObject jObj = new JSONObject(loadJSONFromAsset());
JSONObject js = jObj.getJSONObject("body");
JSONObject jo = js.getJSONObject("name");
System.out.println("test value "+jo.getString("test");

Categories

Resources