How to write junit test case parsing jsonresponse? - java

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);
}
}
}

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/

Why json parser program doesn't find array?

Pls help me to understand why this java program doesn't find array from json file. I didn't find similar type json file via google so pls educate me.
Error:
C:\temp\example.json
org.json.JSONException: JSONObject["result"] not found.
at org.json.JSONObject.get(JSONObject.java:572)
at org.json.JSONObject.getJSONArray(JSONObject.java:765)
at JsonParsingMachine.main(JsonParsingMachine.java:17)
.java content:
import java.io.FileReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.json.*;
public class JsonParsingMachine {
public static void main(String[] args) {
String tiedosto = "C:/temp/example.json";
System.out.println(Paths.get(tiedosto));
try {
String contents = new String((Files.readAllBytes(Paths.get(tiedosto))));
JSONObject o = new JSONObject(contents);
JSONArray res = o.getJSONArray("result");
for (int i = 0; i < res.length(); i++) {
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
json file (example.json)
{
"quoteResponse" : {
"result" : [ {
"language" : "en-US",
"region" : "US",
"quoteType" : "EQUITY",
"quoteSourceName" : "Nasdaq Real Time Price",
"triggerable" : true
} ]
}
}
result array is inside quoteResponse JSONObject. You need to do this instead:
JSONObject o = new JSONObject(contents);
JSONObject quoteResponse = o.getJSONObject("quoteResponse");
JSONArray res = quoteResponse.getJSONArray("result");

Generate JSON from map values

I have written a method which takes map entity and location as parameters, using Jackson object mapper
public class EntityGenerator {
private static void generatePartiallySearchableEntity(Map<String, Set<String>> synMap, String root_dir_loc) throws Exception {
Set < String > namedEntitySet = null;
synMap.put("severity", namedEntitySet);
ObjectMapper mapperobj = new ObjectMapper();
mapperobj.writeValue(new File(root_dir_loc), synMap);
System.out.println("Test.json file created");
}
public static void main(String args[]) throws Exception {
Map < String, Set < String >> sysMap = new HashMap<String, Set<String>>();
Set < String > severityEntitySet = new HashSet<String>();
severityEntitySet.add("Critical");
severityEntitySet.add("Error ");
severityEntitySet.add("Warning ");
severityEntitySet.add("Information ");
sysMap.put("Severity", severityEntitySet);
Set < String > impactEntitySet = new HashSet<String>();
impactEntitySet.add("Inciden");
impactEntitySet.add("Risk");
impactEntitySet.add("Event");
sysMap.put("Imapct", impactEntitySet);
String root_dir_loc = "C:\\Users\\rakshitm\\Documents\\test.json";
generatePartiallySearchableEntity(sysMap, root_dir_loc);
}
I'm getting JSON output like this, like different what I expected from
{"severity":null,"Severity":["Error ","Information ","Critical","Warning "],"Imapct":["Inciden","Risk","Event"]}
I need JSON output of this type
[
{
"value": "event",
"synonyms": [
"event"
]
},
{
"value": "impact",
"synonyms": [
"impact"
]
},
{
"value": "severity",
"synonyms": [
"severity"
]
},
{
"value": "notes",
"synonyms": [
"notes"
]
}
]
See the code below:
package com.abhi.learning.stackoverflow;
import java.util.List;
public class Example {
private String value;
private List<String> synonyms = null;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public List<String> getSynonyms() {
return synonyms;
}
public void setSynonyms(List<String> synonyms) {
this.synonyms = synonyms;
}
}
Main Class:
package com.abhi.learning.stackoverflow;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
Example emp = new Example();
ArrayList<String> al = new ArrayList<String>();
al.add("Critical");
al.add("Error ");
al.add("Warning ");
emp.setSynonyms(al);
emp.setValue("Severity");
Example emp1 = new Example();
ArrayList<String> al1 = new ArrayList<String>();
al1.add("Inciden");
al1.add("Risk");
al1.add("Event");
emp1.setSynonyms(al1);
emp1.setValue("Imapct");
List<Example> lstEx = new ArrayList<Example>();
lstEx.add(emp1);
lstEx.add(emp);
try {
objectMapper.writeValue(new File("target/employee.json"), lstEx);
} catch ( IOException e) {
e.printStackTrace();
}
}
}
This is the json i got :
[
{
"value":"Imapct",
"synonyms":[
"Inciden",
"Risk",
"Event"
]
},
{
"value":"Severity",
"synonyms":[
"Critical",
"Error ",
"Warning "
]
}
]
You can add more Example objects for "events" & "Notes"
You need a Pojo of following specification.
class Event {
private String value;
private List<String> synonyms;
}
Then you make a list of this class and that would parse your Json correctly.
List<Event> events = new ArrayList<>();

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();
}
}
}

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