java.io.FileNotFoundException json file can not find - java

The structure of my java web project is like this:
When I use this code to get the json file,error message said "Caused by:
java.io.FileNotFoundException:
....\resources\properties\highcharts_startYearWeek.json"
How can I get this JSON file and how to modify my code?

I use this code,the problem has been solved.
String jsonPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
jsonPath = jsonPath + "properties/";
startYearWeek = JsonUtil.parseJsonFile(jsonPath+"highcharts_startYearWeek.json", "{startYearWeek}");
System.out.println("startYearWeek:"+startYearWeek);

Related

FileNotFound while File is there

I am using getClassLoader().getResources to find the path for Jsoup to parse.
String path = JsoupDemo1.class.getClassLoader().getResource("student.xml").getPath();
Document document = Jsoup.parse(new File(path), "utf-8");
Elements names = document.getElementsByTag("name");
System.out.println(names.size());
My student.xml has been placed under the src folder in my module "day11_xml" and this code snippet comes from the class JsoupDemo1 in the package cn.itcast.xml.jsoup under the same module of "day11_xml". The error messages reads as follows:
java.io.FileNotFoundException:/Users/dingshun/Downloads/New%20Java%20Projects/demo/out/production/day11_xml/student.xml (No such file or directory)
I don't get it, as I can find the exact file in the given path. I'm confused, but could you guys help me out? Also, I'm new to both Java programming and this forum and if this question sounds silly or my question format is not right, please let me know.
What you're doing looks good. Maybe use the stream version JSoup.parse.
URL url = JsoupDemo1.class.getClassLoader().getResource("student.xml");
InputStream stream = JsoupDemo1.class.getClassLoader().getResourceAsStream("student.xml");
document = Jsoup.parse(stream, "utf-8", url.toURI()toString());
The documentation linked seems to imply it will work with html not xml, so maybe you need to use the other argument which provides a parser?
Actually, it turned out that Jsoup could not find my file because the path name "New%20Java%20Projects" has spaces between them. When I reload the file in a folder which has no spaces in its name, it works out just fine. So it can parse xml using parse​(File in, String charsetName) method. It seems it cannot parse path name which has spaces in it.

How to resolve "Path variable is not sanitized using getCanonicalPath()" SonarQube Issue?

I am trying to validate API Response with Json Schema File.
code snippet:
File schemaFile = new File("file\name\in\String\format");
isTrue("String message", JSONValidationUtil.isJsonValid(schemaFile, responseBody.asString()));
JsonValdationUtil is custom class written which contain methods for schema validation, and responseBody(RestAssured) is my response object after hitting rest api.
My code is integrated with sonarQube server and once I commit my code I am getting below error from sonarqube.
Path variable is not sanitized using getCanonicalPath()
I used file.getCanonicalPath() and file.getCanonicalFile() methods to sanitize my file path, But still I am getting same error.

Error Parsing JSON String to JSONObject in Java

I have an application that stores this JSON String :
String message ="{\"uid\":\"1\",\"streetName\":\"road\",\"city\":\"London\",\"speedLimit\":20}"
Now I want to parse it back to a JSON Object, In order to do so I have this line:
JsonObject object = new JsonParser().parse(message).getAsJsonObject();
I am using Gson Library to parse it and use it as a JSON Object. However, I am getting this exception :
com.google.gson.stream.MalformedJsonException: Expected name at line 1 column 2 path $.
Update 1
I have tried this
String message = "{"uid":"1","streetName":"road","city":"London","speedLimit":20}";
JSONObject object = new JSONObject(message);
Now I get this exception:
Unterminated string at character 28 of {"uid":"1","streetName":"roa
I have tried lots of workarounds from multiple threads on StackOverflow but nothing is working and I have no idea why ?
You can Directly cast it to the JSONObject,
JSONObject response = new JSONObject();
String str = "{\"uid\":\"1\",\"streetName\":\"road\",\"city\":\"London\",\"speedLimit\":20}";
response = new JSONObject(str);
Now the string response has casted as Json response.
you code is fine and should work
please check on the import of the JsonParser in your java file (should be com.google.gson.JsonParser)
let know on the Gson version if the JsonParser is not the issue
your code should work, may be you need to check the dependencies as mentioned before.
I am using this dependency https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.0
here is an sscce that work https://github.com/SalehAly/test-gson
I found my problem.
The String I was processing was malformed for the source. Fixing the string was the answer in here. Nothing was wrong with how I parsed the string.
Thanks for all the answers and the help.

How to pull individual pieces of data from a JSON output String?

In Java, how would I pull the data for just the "data" section in the following JSON output?
{"getuserhashrate":{"data":1425,"runtime":8.2659721374512,"version":"1.0.0"}}
json.get("data") does not work and gives the following error:
Exception in thread "main" org.json.JSONException: JSONObject["data"] not found.
at org.json.JSONObject.get(JSONObject.java:454)
at so4308554.JsonReader.main(JsonReader.java:40)
You have a JSON object. It contains exactly one field: getuserhashrate
{"getuserhashrate": ... }
That field contains another JSON object which has its own fields ("data", "runtime", etc).
{"data":1425,"runtime":8.2659721374512, .. }
From looking at your stack trace, you're using the basic json.org library (or the Android SDK).
You'd parse the JSON and get back the top-level object via:
JSONObject root = new JSONObject(myJsonString);
Then you'd get the object contained in the getuserhashrate field:
JSONObject data = root.getJSONObject("getuserhashrate");
Now you are able to access the fields of that object.
JsonPath is a good tool to extract information from JSON
{"getuserhashrate":{"data":1425,"runtime":8.2659721374512,"version":"1.0.0"}}
String json = yourStringjson;
String data = JsonPath.read(json, "$.getuserhashrate.data");
data will be 1425
Just add the libs and it will be a useful tool if you dont want to create beans to have a full marshall
https://code.google.com/p/json-path/

Need to parse String in XML format to obtain Request Information

I have got a String request in the XML format , which i need to parse it to obtain the Request data from it .
The XML String would be conssiting of a lot of subtags within it , and data is appended in it in the form of CDATA as well as there are >&lt , ini t.
I want to use STAX approach for this .
Please sugesst if theer are any cons wtth this ??
i need this inside a Java Webservice
You can parse your XML file with native PHP function.
EX :
$path = '/my/file/xml.xml';
$file = file_get_contents($path);
$xml = new SimpleXMLElement($file);
And get nodes with :
$value1 = $xml->node[0]->value;
$value2 = $xml->node[1]->value;
There would not be any issues in using DOM parser based STAX API.

Categories

Resources