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

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/

Related

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

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

Append text field data to an existing JSON file in java

I have a text field where user can enter data, once data is received i want to append it to existing JSON file.
I am able to read the existing data and getting the text field value, but while appending the new data with existing data I'm facing problem.
Error:
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 18 path $
Below code :
JSON File :
{"vins":[{"vin":"544554"},{"vin":"54554"}]}
Text field value : String test ="3689";
so it should be appended as :
{"vins":[{"vin":"544554"},{"vin":"54554"},{"vin":"3689"}]}
Filereadwrite class :
public class JSONFIlewrite {
public static String Vinno_Read;
public static List<String> linststring;
public static void main(String[] args) {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new
FileReader("C:\\Amaresh\\Test\\sample_json.json"));
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject);
linststring= new ArrayList();
// loop array
JSONArray msg = (JSONArray) jsonObject.get("vins");
Iterator iterator = msg.iterator();
while (iterator.hasNext()) {
Vinno_Read = iterator.next().toString();
linststring.add(Vinno_Read);
}
String list_string = "";
System.out.println(linststring);
for(String temp:linststring){
list_string += temp;
System.out.println("amar1"+list_string);
}
System.out.println("amar"+list_string);
Vin vin4 = new Vin();
vin4.setVin("76354273462");
Vins vins = new Vins();
vins.addVins(vin4);
Gson gson = new Gson();
//String jsonValue=list_string;
String jsonValue = gson.toJson(list_string).toString();
System.out.println("json--"+jsonValue);
Vins vins1 = gson.fromJson(jsonValue, Vins.class);
System.out.println("ddd"+vins1);
Vin vin = new Vin();
vin.setVin("544554");
vins1.addVins(vin);
jsonValue = gson.toJson(vins1).toString();
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("C:\\Amaresh\\Test\\sample_json.json"));
writer.write(jsonValue);
System.out.println("Test"+jsonValue);
} catch (IOException e) {
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Setter Getter classes :
public class Vin {
#Expose
private String vin;
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;
}
}
public class Vins {
#Expose
List<Vin> vins = new ArrayList<>();
public List<Vin> getVins() {
return vins;
}
public void addVins(Vin vin) {
this.vins.add(vin);
}
}
Main Logic:
you can see 4 blocks in the code
Reading the json file and parsing to a java Object
Casting de java Object to a JSonObject, parsing to a JsonArray and iterating the array printing the JsonElements
Creating a new Vin Object and converting it to a JSON String using Gson.toJson method (2nd part is not required only illustrative purposes)
Creating a JsonWriter, creating a Vins Object and loading it with the original JsonArray and then adding a new element (that correspondents to the new Vin Object created in step #3, finally writing the Vins Object to the [new] file.
Input:
{"vins":[{"vin":"544554"},{"vin":"54554"}]}
Output:
{"vins":[{"vin":"544554"},{"vin":"54554"},{"vin":"3689"}]}
Code
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;
public class JSONFIlewrite {
public static String Vinno_Read;
public static List<String> linststring;
public static void main(String[] args) {
try {
JsonParser parser = new JsonParser();
Object obj = parser.parse(new FileReader("C:\\Amaresh\\Test\\sample_json.json"));
JsonObject jsonObject = (JsonObject) obj;
System.out.println(jsonObject);
linststring = new ArrayList<String>();
// loop array
JsonArray msg = (JsonArray) jsonObject.get("vins");
Iterator<JsonElement> iterator = msg.iterator();
while (iterator.hasNext()) {
Vinno_Read = iterator.next().toString();
System.out.println("Vinno_Read---->" + Vinno_Read);
}
Vin newVin = new Vin();
newVin.setVin("3689");
Gson gson = new Gson();
String json = gson.toJson(newVin);
System.out.println("json---->" + json);
FileWriter file = new FileWriter("C:\\Amaresh\\Test\\sample_json2.json", false);
JsonWriter jw = new JsonWriter(file);
iterator = msg.iterator();
Vins vins = new Vins();
while (iterator.hasNext()) {
vins.addVin(gson.fromJson(iterator.next().toString(), Vin.class));
}
vins.addVin(newVin);
gson.toJson(vins, Vins.class, jw);
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Notes:
Since I don't know what library you are using, I have updated the class names to be compatible to GSON.
I have also changed the method: public void addVins(Vin vin) in Vins Class to public void addVin(Vin vin)
To keep the existing content and append the new content to the end of JSON file:
Example1:
new FileWriter(file,true);
or you can try example02:
FileWriter file= new FileWriter(JSONLPATH,true)

JSON formatting for 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);

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