Failed to read JSON file in new IDE - java

I have an Eclipse project with the following code:
import org.json.*;
import org.json.simple.JSONObject;
import java.io.*;
import java.util.Iterator;
(...)
public static void main( String[] args )
{
String resourceName = "C:\\Users\\Snail_Sniffer\\Desktop\\books.json";
String jsonData = readFile(resourceName);
JSONObject jobj = new JSONObject(jsonData);
(...)
It produces no errors and works as intended, but when I reuse the same code in IntelliJ, it produces following errors:
Error:java: constructor JSONObject in class org.json.simple.JSONObject
cannot be applied to given types;
required: no arguments
found: java.lang.String
reason: actual and formal argument lists differ in length
Error:java: cannot find symbol
symbol: method getString(java.lang.String)
location: variable jobj of type org.json.simple.JSONObject
What is causing the issue and how to workaround it?

I'm not sure which library you are using in eclipse, but org.json.simple.JSONObject does not have constructor with String argument. It has only no argument constructor
public JSONObject()
If you want to parse json string using org.json.simple library you need JSONParser
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(jsonData);

Related

Oracle Java Json not working even after adding classpath

I am using openjdk version 11.0.15 on Debian 4.19. I want to use the JSON library available in Java: javax.json-1.0.jar. After downloading the jar file, I have added the classpath like so:
export CLASSPATH=/Diss/frontend/javax.json-1.0.jar
echo $CLASSPATH:
/Diss/frontend/javax.json-1.0.jar
my code is this:
import javax.json.Json;
import javax.json.JsonReader;
import javax.json.JsonStructure;
import javax.json.JsonObject;
public class ns3_inputs {
public static void main (String[] args)
{
JSONObject obj = new Json.createObjectBuilder();
obj.add("foo", "bar");
obj.build();
}
}
I compile like this: javac -cp .:$CLASSPATH ns3_inputs.java
to which I get the following error:
error: cannot find symbol
JSONObject obj = new Json.createObjectBuilder();
^
symbol: class JSONObject
location: class ns3_inputs
ns3_inputs.java:25: error: cannot find symbol
JSONObject obj = new Json.createObjectBuilder();
^
symbol: class createObjectBuilder
location: class Json
2 errors
The java source code file and the jar file are in the same directory. Am I supposed to place the jar file in a specific path? I am very new to Java so I may be missing something very basic here. I am trying to build a desktop Java application and I cannot use any libraries suitable for android. Please suggest a solution
The class name is JsonObject, not JSONObject.
The following compilation is successful.
~ $ export CLASSPATH=~/Downloads/javax.json-api-1.0.jar
~ $
~ $ cat ns3_inputs.java
import javax.json.Json;
import javax.json.JsonObjectBuilder;
public class ns3_inputs {
public static void main (String[] args)
{
JsonObjectBuilder obj = javax.json.Json.createObjectBuilder();
obj.add("foo", "bar");
obj.build();
}
}
~ $
~ $ javac ns3_inputs.java

class org.json.simple.JSONArray cannot be cast to class org.json.JSONObject

Here is my Java Class
I am getting below Exception,
My Requirement is : Read the Json entire Json file and return it, can come one please help me to figure this out
package Resources;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import com.fasterxml.jackson.core.JsonParser;
public class ObjectRepository {
public static JSONObject readJsonFile(String fileName) throws IOException, Exception {
fileName="C:\\Users\\AamP\\eclipse-workspace\\globalData.json";
JSONParser myParser = new JSONParser();
Object myObject = myParser.parse(new FileReader(fileName));
JSONObject myJsonObject = (JSONObject) myObject;
return myJsonObject;
}
}
java.lang.ClassCastException: class org.json.simple.JSONArray cannot be cast to class org.json.JSONObject (org.json.simple.JSONArray and org.json.JSONObject are in unnamed module of loader 'app')
at Resources.ObjectRepository.readJsonFile(ObjectRepository.java:41)
at Resources.BaseClass.initializeDriver(BaseClass.java:57)
at Nimbly.nimbly_ui.SampleTest.loadUrl(SampleTest.java:29)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:62)
at org.testng.internal.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:385)
at org.testng.internal.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:321)
at org.testng.TestRunner.invokeTestConfigurations(TestRunner.java:637)
at org.testng.TestRunner.beforeRun(TestRunner.java:627)
at org.testng.TestRunner.run(TestRunner.java:589)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:377)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:371)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:332)
at org.testng.SuiteRunner.run(SuiteRunner.java:276)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1212)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1134)
at org.testng.TestNG.runSuites(TestNG.java:1063)
at org.testng.TestNG.run(TestNG.java:1031)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Why not directly use org.json.JSONObject
JSONObject myJsonObject = new JSONObject(new FileReader(fileName));
public static void main(String[] args) {
try {
FileReader fr = new FileReader("path/to/file.json");
JSONParser parser = new JSONParser();
JSONArray jObj = (JSONArray) parser.parse(fr);
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
Use JSONObject for JSON like
{
"id":"101",
"name":"Tarun"
}
and JSONArray for array of JSON like
[
{"id":"1","name":"ankur"},
{"id":"2","name":"mahajan"}
]
you can wrap it in a func. and return the jObj according to your needs.
A JSON Object looks like:
{"foo": "bar", ... }
while a JSON Array looks like: ["foo", "bar", ...].
If you read the documentation for org.json.simple you'll see that parse returns Object and that org.json.JSONObject is not part of that library.
If you want to use org.json.simple, then your readJsonFile method will need to return Object, unless you are certain that the JSON file contains a JSON Array, i.e. ["foo", "bar", ...], in which case you can cast to org.json.simple.JSONArray.
This will give you a ClassCastException when your JSON file contains a JSON Object instead of an array.

Read JSON file with JSONParser not available in the jarfile

I am trying to read a json file and convert it to the jsonObject and when I searched on how to do it, I came across the method to user
JSONParser parser= new JSONParse();
But the version of org.json I am using in the code is "20180803". It does not contain JSONParser. Has it been removed from the org.json package? If so what is the new class or method that I could use to read a json file and convert it to a json object.
My dependency is given below :
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
Hi you can use simple JSON. You just need to add in your pom.xml file:
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
</dependency>
Sample code
public static JSONObject convertJsonStingToJson(String jsonString) {
JSONParser parser = new JSONParser();
return json = (JSONObject) parser.parse(jsonString);
}
org.json library has very simple API which does not have JSONParser but has JSONTokener. We can construct JSONObject or JSONArray directly from String:
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonApp {
public static void main(String[] args) {
// JSON Object
String object = "{\"p1\":\"v1\", \"p2\":2}";
JSONObject jsonObject = new JSONObject(object);
System.out.println(jsonObject);
// JSON Array
String array = "[{\"p1\":\"v1\", \"p2\":2}]";
JSONArray jsonArray = new JSONArray(array);
System.out.println(jsonArray);
}
}
Above code prints:
{"p1":"v1", "p2":2}
[{"p1":"v1","p2":2}]
You need to notice that it depends from JSON payload which class to use: if JSON starts from { use JSONObject, if from [ - use JSONArray. In other case JSON payload is invalid.
As it mentioned in other answers, if you can you should definitely use Jackson or Gson
Add following dependency in build file
//json processing
implementation("com.fasterxml.jackson.core:jackson-core:2.9.8")
implementation("com.fasterxml.jackson.core:jackson-annotations:2.9.8")
implementation("com.fasterxml.jackson.core:jackson-databind:2.9.8")
a.json file
{
"a": "b"
}
code:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.FileInputStream;
import java.io.InputStream;
public class App {
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
InputStream input = new FileInputStream("a.json");
JsonNode obj = objectMapper.readTree(input);
System.out.println(obj.get("a")); // "b"
}
}
The short answer to your question is: No, it was not removed, because it never existed.
I think you are mentioning a library, and trying to use another one. Anyway, if you really want to use org.json, you can find how here
JSONObject jsonObject = new JSONObject(instanceOfClass1);
String myJson = jsonObject.toString();

Method put()-error in Java while putting data in JsonObject.

I have a question about my error code. I am working on a project with Angular, Java, Spark and an SQL database.
The method contains a prepared statement with an SQL Select statement. In the whileloop wants to go through as long as a result is found. Pack the queried data into a Json object, and these Json objects into a Json array.
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import finanzplanpackage.connection.ConnectionConfiguration;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.lang.String;
import java.util.logging.Level;
import java.util.logging.Logger;
public class n_paresmodul {
private ConnectionConfiguration c = new ConnectionConfiguration();
public String viewdata() {
String data = "";
JsonArray ja = new JsonArray();
try{
PreparedStatement pre = c.getconn().prepareStatement("SELECT * FROM n_pares");
ResultSet res = pre.executeQuery();
while (res.next()) {
JsonObject jo = new JsonObject();
jo.put("account_id", res.getInt("account_id"));
jo.put("mandant_id", res.getInt("mandant_id"));
jo.put("id", res.getInt("id"));
jo.put("sourcedata", res.getString("sourcedata"));
ja.add(jo);
}
data = ja.toString();
} catch(
SQLException ex)
{
Logger.getLogger(n_paresmodul.class.getName()).log(Level.SEVERE, null, ex);
}
return data;
}
When compiling, the compiler throws me the following error message.
symbol: method put (java. lang. String, int)
location: variable jo of type com. google. gson.JsonObject
enter image description here
Can someone please help me and tell me what I'm doing wrong with the put-method?
thank you
com.google.gson.JsonObject does not have any method put()
You should try using addProperty("account_id", res.getInt("account_id"))

String to json conversion issue

I am trying to convert a string to JSONObject object using the below code,but i am getting
Exception in thread "main" java.lang.ClassCastException:
org.json.simple.JSONObject cannot be cast to net.sf.json.JSONObject .
Source:
import net.sf.json.JSONObject;
import org.json.simple.parser.JSONParser;
public static void run(JSONObject jsonObject) {
System.out.println("in run--");
}
public static void main(String[] args) throws Exception {
System.out.println("here");
String json = "{\"task\": \"com.ge.dbt.workers.surveytoexcel.worker.SurveyWorker\",\"prod_id\": 12345,\"survey_id\": 5666,\"person_id\": 18576567,\"req_date\": \"12\12\2012\"}";
JSONObject jsonObj;
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);
jsonObj = (JSONObject) obj;
run(jsonObj);
}
What is wrong here?
You've imported JSONObject from the wrong package. Change this line:
import net.sf.json.JSONObject;
to this:
import org.json.simple.JSONObject;
Implementing the following solution, You don't even have to bother about a parser...
The Problem here is that u're trying to cast a object of type org.json.simple.JSONObject to net.sf.json.JSONObject. You might wanna try The package org.codehaus.jettison.json.JSONObject. that is enough to do all the required things.
Simple Example:
First, Prepare a String:
String jStr = "{\"name\":\"Fred\",\"Age\":27}";
Now, to parse the String Object, U just have to pass the String to the JSONObject(); constructor method
JSONObject jObj = new JSONObject(jStr);
That should do it and voila! You have a JSONObject.
Now you can play with it as u please.
How So Simple ain't it?
The Modified version of the Code might look like:
import net.sf.json.JSONObject;
import org.codehaus.jettison.json.JSONObject;
public static void run(JSONObject jsonObject) {
System.out.println("in run-- "+jsonObject.getInt("person_id"));
}
public static void main(String[] args) throws Exception {
System.out.println("here");
String json = "{\"task\": \"com.ge.dbt.workers.surveytoexcel.worker.SurveyWorker\",\"prod_id\": 12345,\"survey_id\": 5666,\"person_id\": 18576567,\"req_date\": \"12\12\2012\"}";
JSONObject jsonObj = new JSONObject(json);
run(jsonObj);
}
with JSON, It's SssOooooooo simple

Categories

Resources