JSON formatting for Java - java

Hi I need to produce a JSON file with a certain format. I'm stuck and advice on how to proceed with this. My code is below:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.io.FileWriter;
import java.io.IOException;
public class Student {
public static void main(String[] args) {
int a = -7;
int b = 7;
int k = 103;
int order = 109;
int px = 60;
int py = 76;
JSONObject obj = new JSONObject();
obj.put("name", "JEAN-LUC PALMYRE");
obj.put("srn", "120299364");
obj.put("ecc","");
try (FileWriter file = new FileWriter("Jean-LucPalmyre_120299364_CO3326_cw1.json"))
{
file.write(obj.toJSONString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(obj);
}
The output should be like this:
{
"name": "MARK ZUCKERBERG",
"srn": "000000001",
"ecc": {
"a": -2,
"b": 13,
"k": 103,
"order": 109
}
}

try this:
JSONObject obj = new JSONObject();
obj.put("name", "JEAN-LUC PALMYRE");
obj.put("srn", "120299364");
JSONObject objEcc = new JSONObject();
objEcc.put("a",a);
objEcc.put("b",b);
objEcc.put("k",k);
objEcc.put("order",order);
obj.put("ecc",objEcc);

Related

JSONObject["data"] not found in Test (Junit5) [duplicate]

I want to read this JSON file with java using json library
"ListeCar": [
{
"id": "R",
"size": "2",
"Orientation": "Horizontal",
"Position": {
"Row": "2",
"Column": "0"
}
}
This is my java code :
package rushhour;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.*;
public class JsonClass {
public static void main(String[] args) throws IOException, JSONException {
try{
JSONObject obj = new JSONObject(new FileReader("C:\\Users\\Nuno\\Desktop\\School\\clg-g41326\\RushHourJson.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray Liste = obj.getJSONArray("ListeCar");
String listeCar = Liste.getJSONObject(0).getString("id");
for (int i = 0; i <Liste.length(); i++) {
String id = Liste.getJSONObject(i).getString("id");
System.out.println(id);
String size = Liste.getJSONObject(i).getString("size");
System.out.println(size);
String Orientation = Liste.getJSONObject(i).getString("Orientation");
System.out.println(Orientation);
String Position = Liste.getJSONObject(i).getString("Position");
System.out.println(Position);
}
}catch(JSONException e){
e.printStackTrace();
}
}
}
I'm doing this in netbeans and it's kind a my first time using Json !
I want just to do a system.out from this little json code. I don't know why he's not finding the file that i put in the new JSONObjet ...
{
"ListeCar":[
{
"id":"R",
"size":"2",
"Orientation":"Horizontal",
"Position":{
"Row":"2",
"Column":"0"
}
}]
}
try placing this in your .json file
your json is not valid... try placing it in this site to check for it's validity.... http://json.parser.online.fr/
And the code for the correct output....
public static void main(String[] args) throws IOException, JSONException, ParseException {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("/home/Desktop/temp.json"));
JSONObject objJsonObject = new JSONObject(obj.toString());
System.out.println(objJsonObject);
JSONArray Liste = objJsonObject.getJSONArray("ListeCar");
String listeCar = Liste.getJSONObject(0).getString("id");
for (int i = 0; i < Liste.length(); i++) {
String id = Liste.getJSONObject(i).getString("id");
System.out.println(id);
String size = Liste.getJSONObject(i).getString("size");
System.out.println(size);
String Orientation = Liste.getJSONObject(i).getString("Orientation");
System.out.println(Orientation);
String Position = Liste.getJSONObject(i).getJSONObject("Position").toString();
System.out.println(Position);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You forgot to parse json... which is done in the above code.... a link about the tutorial on how to do this is as follows:: http://crunchify.com/how-to-read-json-object-from-file-in-java/

How to write junit test case parsing jsonresponse?

I am trying to write a test case in which the condition is I have to read a json file then if valuesdata is true then it must have values attribute and when it is false then it should have sql attribute
{
"data": [
{
"valuesdata": true,
"values": [
{
"id": "1"
}
]
},
{
"valuesdata": false,
"sql": "select * from data"
}
]
}
This is what I was trying to write , any help is appreciated
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class Test{
#Test
#DisplayName("If Json valuesdata is true it should have values attribute")
public void dropdownJsonValueIsStaticTrue() throws Exception {
String content = new String(Files.readAllBytes(Paths.get(input_file_path)));
JSONObject jsonObjects = new JSONObject(content);
jsonObjects.getJSONArray("data").getJSONObject(0).getBoolean("valuesdata");
}
}
You can consider that :
#Test
public void dropdownJsonValueIsStaticTrue() throws Exception {
String content = new String(Files.readAllBytes(Paths.get(input_file_path)));
JSONObject jsonObjects = new JSONObject(content);
JSONArray datas = jsonObjects.getJSONArray("data");
for (int i = 0 ; i < datas.length(); i++) {
JSONObject data = datas.getJSONObject(i);
boolean valuesdata = data.getBoolean("valuesdata");
if(valuesdata) {
assertTrue(data.getJSONArray("values") != null);
} else {
assertTrue(data.getString("sql") != null);
}
}
}

How to remove unnecessary object names in String of JSONArray?

I have JSONArray in String format as follows :
{
"productsList": [{
"map": {
"productSubcategory": "Levensverzekering",
"nameFirstInsured": "Akkerman"
}
},
{
"map": {
"productSubcategory": "Lineair dalend",
"nameFirstInsured": "Akkerman"
}
}
]
}
I want to convert this String as follows :
{
"productsList": [{
"productSubcategory": "Levensverzekering",
"nameFirstInsured": "Akkerman"
},
{
"productSubcategory": "Lineair dalend",
"nameFirstInsured": "Akkerman"
}
]
}
I have converted JSONArray to String so need operation as on the String on provided String in JSON format.
How I can change the String as required? What should I put in jsonString.replaceAll("","") function?
There is no easy way to do this, you have to do something like this.
OUTPUT IS:
{
"productsList":[
{
"productSubcategory":"Levensverzekering",
"nameFirstInsured":"Akkerman"
},
{
"productSubcategory":"Lineair dalend",
"nameFirstInsured":"Akkerman"
}
]
}
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class test {
public static void main(String[] args) throws IOException, InterruptedException {
JSONParser parser = new JSONParser();
JSONObject newObj = new JSONObject();
try {
Object obj = parser.parse(new FileReader("test.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray arr = (JSONArray) jsonObject.get("productsList");
JSONArray newArr = new JSONArray();
for(int i = 0 ; i < arr.size();i++){
JSONObject object = (JSONObject) arr.get(i);
JSONObject a = (JSONObject) object.get("map");
newArr.add(a);
}
newObj.put("productsList", newArr);
System.out.println(newObj);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Structure JSOUP content to JSON

I extract some data from a http site and now I want to format this using JSON . I watched some examples but i don't understand how to do that exactly .I want something like that :
{
Product name:"Samsung..."
{ review 1:"..."
review 2:"..."
}
}
Also my code don't iterate over all reviews, it stops at page 1 ,and there is 10 more pages and i want to get like 20-30 reviews at least. There is what i did until now :
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class JsoupMain {
private static int nr = 1;
public static void main(String[] args) {
Document document = null;
try {
document = Jsoup.connect("http://www.emag.ro/telefon-mobil-samsung- galaxy-j5-2016-dual-sim-16gb-4g-gold-sm-j510fzdurom/pd/DQD3B7BBM/").get();
String title = document.title();
System.out.println("Title: " + title);
Elements review = document.select("div.product-review-body");
for (Element rev : review) {
System.out.println("Review : " + nr + " :" + rev.text() + "\n");
nr++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
See this answer for a similar question - Parsing table html with Jsoup In your case it might look like this:
JSONObject root = new JSONObject();
JSONArray reviews = new JSONArray();
root.put("name", "Product Name");
for (int i=0; i < elements.size(); i++){
JSONObject review = new JSONObject();
review.put("review"+i , elements.get(i).text());
reviews.add(review);
}
root.put("reviews", reviews);
The JSON output for root would look like this:
{
"name":"Product Name",
"reviews":[
{
"review0":"ok"
},
{
"review1":"awesome"
}
]
}
I want to make this code to show info exactly like that:
{ Reviews:
{ review 1: "..."}
{ review 2: "..."}
................
................
}
In present my code is printing info's like that: "Reviews":[[{"Review 0":"Foarte multumit Un telefon foarte bun. Ce m-a impresionat este camera foto care face niste poze foarte bune"},{"R............}
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class JsoupMain {
private static int nr = 1;
public static void main(String[] args) {
Document document = null;
try {
document = Jsoup.connect("http://www.emag.ro/telefon-mobil-samsung-galaxy-j5-2016-dual-sim-16gb-4g-gold-sm-j510fzdurom/pd/DQD3B7BBM/").get();
String title = document.title();
System.out.println("Product name : " + title);
Elements review = document.select("div.product-review-body");
JSONObject mainObject = new JSONObject();
JSONObject root = new JSONObject();
JSONArray list = new JSONArray();
root.put("Product name", title);
for (int i = 0; i < review.size(); i++) {
JSONObject revieww = new JSONObject();
revieww.put("Review " + i, review.get(i).text());
list.put(revieww);
}
mainObject.accumulate("Reviews", list);
System.out.println(mainObject);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Replace your code from Elements review = document.select("div.product-review-body");... to ... System.out.println(mainObject); with the following code snippet.
Elements review = document.select("div[class=product-review-body]");
JSONObject parent = new JSONObject();
parent.put("Product name", title);
JSONArray reviews = new JSONArray();
int i = 1;
for (Element rev : review) {
reviews.put(new JSONObject().put("review" + i, rev.text()));
i++;
}
parent.put("Reviews", reviews);
System.out.println(parent);
Hope this helps.

org.json.JSONException: JSONObject["ListeCar"] not found

I want to read this JSON file with java using json library
"ListeCar": [
{
"id": "R",
"size": "2",
"Orientation": "Horizontal",
"Position": {
"Row": "2",
"Column": "0"
}
}
This is my java code :
package rushhour;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.*;
public class JsonClass {
public static void main(String[] args) throws IOException, JSONException {
try{
JSONObject obj = new JSONObject(new FileReader("C:\\Users\\Nuno\\Desktop\\School\\clg-g41326\\RushHourJson.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray Liste = obj.getJSONArray("ListeCar");
String listeCar = Liste.getJSONObject(0).getString("id");
for (int i = 0; i <Liste.length(); i++) {
String id = Liste.getJSONObject(i).getString("id");
System.out.println(id);
String size = Liste.getJSONObject(i).getString("size");
System.out.println(size);
String Orientation = Liste.getJSONObject(i).getString("Orientation");
System.out.println(Orientation);
String Position = Liste.getJSONObject(i).getString("Position");
System.out.println(Position);
}
}catch(JSONException e){
e.printStackTrace();
}
}
}
I'm doing this in netbeans and it's kind a my first time using Json !
I want just to do a system.out from this little json code. I don't know why he's not finding the file that i put in the new JSONObjet ...
{
"ListeCar":[
{
"id":"R",
"size":"2",
"Orientation":"Horizontal",
"Position":{
"Row":"2",
"Column":"0"
}
}]
}
try placing this in your .json file
your json is not valid... try placing it in this site to check for it's validity.... http://json.parser.online.fr/
And the code for the correct output....
public static void main(String[] args) throws IOException, JSONException, ParseException {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("/home/Desktop/temp.json"));
JSONObject objJsonObject = new JSONObject(obj.toString());
System.out.println(objJsonObject);
JSONArray Liste = objJsonObject.getJSONArray("ListeCar");
String listeCar = Liste.getJSONObject(0).getString("id");
for (int i = 0; i < Liste.length(); i++) {
String id = Liste.getJSONObject(i).getString("id");
System.out.println(id);
String size = Liste.getJSONObject(i).getString("size");
System.out.println(size);
String Orientation = Liste.getJSONObject(i).getString("Orientation");
System.out.println(Orientation);
String Position = Liste.getJSONObject(i).getJSONObject("Position").toString();
System.out.println(Position);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You forgot to parse json... which is done in the above code.... a link about the tutorial on how to do this is as follows:: http://crunchify.com/how-to-read-json-object-from-file-in-java/

Categories