How to create multi level JSON data using JSONObject in servlet - java

I need to create JSON data like below,
{
"min": {
"week": "1",
"year": "2014"
},
"max": {
"week": "14",
"year": "2017"
}
}
But JSONObject accepts only "id","value" format.
So how can I create JSON data using JSONObject like mentioned above.

That is very easy, here is an example:
JSONObject min = new JSONObject();
min.put("week", "1");
min.put("year", "2014");
JSONObject max = new JSONObject();
max.put("week", "14");
max.put("year", "2017");
JSONObject json= new JSONObject();
stats.put("min", min);
stats.put("max", max);
System.out.println(json.toString());

Tested this in eclipse already for you.
`
String s = "{ \"min\": { \"week\": \"1\", \"year\": \"2014\" }, \"max\": { \"week\": \"14\", \"year\": \"2017\" } }";
JSONParser parser = new JSONParser();
try {
JSONObject json = (JSONObject) parser.parse(s);
System.out.println(json.get("min"));
// this will output
//{"week":"1","year":"2014"}
} catch (Exception e){
e.printStackTrace();
}
`

Related

2D JSON Array Not Generated in Correctly Java

I'm trying to generate 2d JSON Array in Java using Json Object, JSON Array. The 2d array being generated is valid but the ordering of elements is wrong.
Java Code...
JSONObject root1 = new JSONObject();
JSONObject c01 = new JSONObject();
JSONObject c11 = new JSONObject();
JSONObject attachment = new JSONObject();
JSONObject payload = new JSONObject();
JSONArray arrayButton= new JSONArray();
JSONArray arrayelements= new JSONArray();
JSONObject elementsObj = new JSONObject();
JSONObject defaultAction = new JSONObject();
root1.put("recipient", c01);
root1.put("message", c11);
c01.put("id", userId);
c11.put("attachment", attachment);
attachment.put("type", "template");
attachment.put("payload", payload);
payload.put("template_type", "generic");
payload.put("elements", arrayelements);
arrayelements.put(elementsObj);
elementsObj.put("title", "Sample Title");
elementsObj.put("image_url", "https://google.com/");
elementsObj.put("subtitle", "Sample Sub Title");
elementsObj.put("default_action", defaultAction);
defaultAction.put("type", "web_url");
defaultAction.put("url", "https://www.google.com/");
defaultAction.put("messenger_extensions", "true");
defaultAction.put("webview_height_ratio", "tall");
defaultAction.put("fallback_url", "https://www.google.com/");
elementsObj.put("buttons", arrayButton);
JSONObject buttons1 = new JSONObject();
buttons1.put("type", "web_url");
buttons1.put("url", "https://google.com");
buttons1.put("title", "show website");
arrayButton.put(buttons1);
JSONObject buttons2 = new JSONObject();
buttons2.put("type", "postback");
buttons2.put("title", "Hi There");
buttons2.put("payload", "sample payload");
arrayButton.put(buttons2);
Expected Output
{
"recipient":{
"id":"USER_ID"
},
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"generic",
"elements":[
{
"title":"Sample title",
"image_url":"https://google.com/company_image.png",
"subtitle":"We\'ve got the right hat for everyone.",
"default_action": {
"type": "web_url",
"url": "https://google.com/",
"messenger_extensions": true,
"webview_height_ratio": "tall",
"fallback_url": "https://google.com/"
},
"buttons":[
{
"type":"web_url",
"url":"https://google.com",
"title":"View Website"
},{
"type":"postback",
"title":"Start Chatting",
"payload":"Sample payload"
}
]
}
]
}
}
}
}
Current Output
{
"recipient":{
"id":"988459377921053"
},
"message":{
"attachment":{
"payload":{
"elements":[
{
"buttons":[
{
"type":"web_url",
"title":"show website",
"url":"https://google.com"
},
{
"payload":"sample payload",
"type":"postback",
"title":"Hi There"
}
],
"image_url":"https://s3-ap-southeast-1.amazonaws.com/fls-items-dev/sample-item-4-95/post/sample-item-4-95-primary-4495.png",
"subtitle":"Sample Sub Title",
"title":"Sample Title",
"default_action":{
"fallback_url":"https://www.frrndlease.com/",
"webview_height_ratio":"tall",
"messenger_extensions":"true",
"type":"web_url",
"url":"https://www.frrndlease.com/ItemDetails?uid=wilson-kid-235"
}
}
],
"template_type":"generic"
},
"type":"template"
}
}
}
The order of buttons array, objects template_type & type are inverse. I'm creating nested Json objects and adding them from the outer level to the inner level still the output JSON is not as expected. Can't understand where I'm going wrong.

Parsing and retrieving elements in a JSON Java

JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:/Users/dan/Documents/rental.txt"));
JSONObject jsonObject = (JSONObject) obj;
for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println(jsonObject.get(key));
}
} catch (Exception e) {
e.printStackTrace();
}
Following is the JSON String:
{
"Search": {
"VehicleList": [
{
"sipp": "CDMR",
"name": "Ford Focus",
"price": 157.85,
"supplier": "Hertz",
"rating": 8.9
},
{
"sipp": "FVAR",
"name": "Ford Galaxy",
"price": 706.89,
"supplier": "Hertz",
"rating": 8.9
}
]
}
}
}
Hi, I can iterate over the whole JSON object with my code but right now I want to print out the name of a vehicle and the price of the vehicle individually. Any help would be appreciated, I am a beginner when it comes to working with JSON.
Your JSON is structured like this JsonObject -> JsonArray-> [JsonObject]
With that in mind you can access the name and price with this
Object obj = parser.parse(new FileReader("C:/Users/dan/Documents/rental.txt"));
JSONArray jsonArray = (JSONObject) obj.getJsonArray("VehicleList");
for(JSONObject jsonObject : jsonArray){
System.out.println(jsonObject.getString("name") + " " + jsonObject.getDouble("price"))
}
}
Depending on your import library it may deviate from the above but the concept is the same.
You need to iterate over the json. For example.
$.Search.VehicleList[0].price will give you [157.85]
$.Search.VehicleList[1].price will give you [706.89]
http://www.jsonquerytool.com/ will come handy for you :)

Removing simple object from JSON request

I wrote a small code to validate that my request fails when some part of it is removed.I want to remove the product element and its value.
Here's the request
{
"product": "tv",
"price": "45",
"payment": {
"credit_card": {
"number": "1234567891234567",
"type": "Visa",
"expire_month": 10,
"expire_year": 2019,
"cvv2": 999,
"first_name": "John",
"last_name": "Smith"
}
}
}
This is the code snippet -
JSONParser parser = new JSONParser();
String requestFile = System.getProperty("user.dir") + "/src/test/resources/request/request.json";
logger.info("Loading request file: " + requestFile);
Object obj = parser.parse(new FileReader(requestFile));
JSONObject jsonObject = (JSONObject) obj;
//fails on the below line saying Java.lang.String cannot be cast to org.json.simple.JSONObject
// What's the alternative?
logger.info("printing json object "+jsonObject.get("product"));
jsonObject = (JSONObject) jsonObject.remove("product");
System.out.println("Now the request is "+jsonObject);
I was able to resolve this problem.
Here's the code snippet after making changes in it.
JSONParser parser = new JSONParser();
String requestFile = System.getProperty("user.dir") + "/src/test/resources/request/original_request.json";
logger.info("Loading request file: " + requestFile);
Object obj = parser.parse(new FileReader(requestFile));
Object jsonObject = (JSONObject) obj;
//remove product_name
((HashMap) jsonObject).remove("product");
logger.info("New request "+jsonObject);

How to read a JSON file using JSON.simple library?

I'm trying to parse a json file using json simple library but I'm having some trouble getting the code to parse the json file. I've done some searching but every example's json file is formatted differently from the one I'm using. I'm able to query the full json file, but I can't get a specific piece of information from my json file and add it to a list (the list turns up empty).
The json file in question (this is a snippet of the original file for simplicity's sake):
{
"status": "ok",
"count": "2",
"data":{
"1":{
"country": "U.S.A.",
"name": "Jeremy",
"id": 1
},
"3":{
"country": "U.K.",
"name": "Dell",
"id": 3
}
}
}
The code I've tried using:
List<String> list = new ArrayList<String>();
String json = myJSONFile; // myJSONFile is a place holder for the location of the file.
JSONObject jsonObject = (JSONObject) JSONValue.parse(json);
JSONObject data = (JSONObject) jsonObject.get("data");
for (int x = 0; y > data.size(); y++)
{
JSONObject id = (JSONObject) data.get(y + "");
list.add((String) id.get("name");
}
// Used to show if the list is empty or not.
JOptionPane.showMessageDialog(null, list);
As pointed out in the comments, you JSON isn't a valid one. You can try parsing it here.
The correct JSON appears to be:
{
"status": "ok",
"count": "2",
"data": {
"1": {
"country": "U.S.A.",
"name": "Jeremy",
"id": 1
},
"3": {
"country": "U.K.",
"name": "Jeremy",
"id": 3
}
}
}
A couple of errors in your code:
1) You are trying to parse the JSON file location without reading it. You need to first read the file containing JSON string
List<String> list = new ArrayList<String>();
String json = "..\\json.txt";
JSONParser parser = new JSONParser();
Object parsed = parser.parse(new FileReader(json));
JSONObject jsonObject = (JSONObject) parsed;
2) Your loop doesn't make much sense. Here you want to try and iterate over the keys returned by your JSONObject represented by data
JSONObject data = (JSONObject) jsonObject.get("data");
Iterator<?> keys = data.keySet().iterator();
while (keys.hasNext()) {
if (data.get(keys.next()) instanceof JSONObject) {
JSONObject id = (JSONObject) data.get(keys.next());
list.add((String) id.get("name"));
System.out.println("Yo => " + (String) id.get("name"));
}
}
Here is the full working sample, modify per your need to make it more generic and best practices:
public static void main(String... args) {
try {
List<String> list = new ArrayList<String>();
String json = "..\\json.txt"; //Location of your json file
JSONParser parser = new JSONParser();
Object parsed = parser.parse(new FileReader(json));
JSONObject jsonObject = (JSONObject) parsed;
JSONObject data = (JSONObject) jsonObject.get("data");
Iterator<?> keys = data.keySet().iterator();
while (keys.hasNext()) {
if (data.get(keys.next()) instanceof JSONObject) {
JSONObject id = (JSONObject) data.get(keys.next());
list.add((String) id.get("name"));
System.out.println("Yo => " + (String) id.get("name"));
}
}
// Used to show if the list is empty or not.
JOptionPane.showMessageDialog(null, list);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Output:

JSON array from Django to Android

I'm having trouble trying to parse a json array string sent from Django to an Android. This is the format of the json string.
[
{
"pk": 1,
"model": "brete.brete",
"fields": {
"contenido": "93iw09if",
"fecha": "2011-05-07 03:06:40",
"codigo_confirmacion": "",
"correo": "oij8#gmail.com",
"activado": false,
"titulo": "234"
}
},
{
"pk": 2,
"model": "brete.brete",
"fields": {
"contenido": "asoidjfdiso",
"fecha": "2011-05-07 03:08:09",
"codigo_confirmacion": "",
"correo": "oijoiji#oijoi.com",
"activado": false,
"titulo": "ijj"
}
}
]
etc
This is how I'm grabbing the data:
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Brete resultRow = new Brete();
resultRow.contenido = json_data.getString("contenido");
resultRow.fecha = json_data.getString("fecha");
resultRow.correo = json_data.getString("correo");
arrayOfWebData.add(resultRow);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
I'm trying to get the data of 'contenido', 'fecha' and 'correo' But I'm not getting any rows displayed. This is not the whole code and maybe the problem lies somewhere else, but I have a hunch this might be a problem of not parsing correctly the nested json with json_data.getString(). Any help is appreciated.
Before you grab your fields you actually have to reach for the "fields" object:
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject buf = jArray.getJSONObject(i);
JSONObject json_data = buf.getJSONObject("fields");
Brete resultRow = new Brete();
resultRow.contenido = json_data.getString("contenido");
resultRow.fecha = json_data.getString("fecha");
resultRow.correo = json_data.getString("correo");
arrayOfWebData.add(resultRow);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}

Categories