This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I'm trying to read parameters for a function from a JSON file, but I always got a empty string.
This is my JSON file
{
"prova":"https://urltest",
"reale":"https://url"
}
and my code is
String key_param = "folder/param.json";
File param = new File ("/tmp/" + key_param);
/*
...
CODE FOR CHECKING FILE EXISTENCE
...
*/
JSONParser new_pars = new JSONParser();
Reader myreader = new FileReader(param);
JSONObject json_param = (JSONObject) new_pars.parse(myreader);
String url = new String();
if (ambiente == "prova") //<-- this has been previously set in the code
url = (String) json_param.get("prova");
else if (ambiente == "reale")
url = (String) json_param.get("reale");
System.out.println("url = " + url);
I always get url = from the execution.
What's wrong?
EDIT
It's not the json handling which is faulty, but my attempt to compare strings in Java using ==
Are there any errors when you use jsonobject.get(value) ?
Same as #Dave Newton's answer. You can not compare to string with operation ==. You should use equals or equalsIgnorecase to compare
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 8 months ago.
I have the following service for to get values inside a string document, this service is called inside a for, getting the data for every flight and then generate a PDF.
I'm getting the Index 2 out of bounds for length 1 when try to call the service, this is the code:
private Map<String, Object> readFileLsd(String content) {
Map<String, Object> mapResult = new LinkedHashMap<>();
try {
Reader inputString = new StringReader(content);
BufferedReader br = new BufferedReader(inputString);
String line;
String TotalBaggagesCargo = "";
String PASSENGER = "";
String TOTAL_TRAFFIC = "";
String validCharacters = "[\\x00-\\x1F]|[\\x21-\\x2c]|[\\x3B-\\x40]|[\\x5B-\\x60]|[\\x7B-\\xFF]";
while ((line = br.readLine()) != null) {
line = line.replaceAll(validCharacters, "").trim();
if (line.startsWith("LOAD IN COMPARTMENTS")) {
TotalBaggagesCargo = line;
}
if (line.startsWith("PASSENGER/CABIN BAG")) {
PASSENGER = line;
}
if (line.startsWith("TOTAL TRAFFIC LOAD")) {
TOTAL_TRAFFIC = line;
}
}
mapResult.put("TotalBaggagesCargo", TotalBaggagesCargo.trim().replaceAll("\\s+", " ").split(" ")[3]);
mapResult.put("PASSENGER", PASSENGER.trim().replaceAll("\\s+", " ").split(" ")[2]);
mapResult.put("TOTAL_TRAFFIC", TOTAL_TRAFFIC.trim().replaceAll("\\s+", " ").split(" ")[3]);
} catch (Exception e) {
e.printStackTrace();
}
return mapResult;
}
Underlying Problem
The line which starts with PASSENGER/CABIN BAG apparently has only one whitespace character and when you split it by a space it results in a String array with only one entry.
Possible solution
If the amount of passengers is sometimes not present in the input String, then you could make the put of key conditional.
String[] passengers = PASSENGER.trim().replaceAll("\\s+", " ").split(" ");
if (passenger.length > 2) mapResult.put("PASSENGER", passengers[2]);
This might bring different problems later in your program. So before working around it, you must try to understand, why it is absent. If it is reasonable that it is missing, then the workaround is acceptable, maybe you will need an else-case like that
else mapResult.put("PASSENGER", "");
when the key has to be present later on.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
user have to write an email in multiple lines and stop the input when ".." (two dots) are entered by the user. then the email should be saved to the variable but the variable saves the last input which are the two dots.
this is my code
any changes?
BufferedReader inl = new BufferedReader(new InputStreamReader(System.in));
String email_data;
System.out.println("Data: ");
do{
email_data = inl.readLine();
} while(email_data != "..");
Append the input to your variable instead of overriding it.
Also, don't use '!=' or '==' on Strings - use the .equals() method instead.
BufferedReader inl = new BufferedReader(new InputStreamReader(System.in));
String email_data = "";
String input;
System.out.println("Data: ");
do{
input = inl.readLine();
if (!input.equals("..")) {
email_data += input;
}
} while(!input.equals(".."));
This question already has answers here:
Convert Json Array to normal Java list
(16 answers)
Closed 3 years ago.
I am using openjdk 11 and I am calling an api that is returning content type json. I parsing the response and converting into a string like this ( Need to do it this way as I am expecting responses in different formats/structure):
HttpEntity entity = response.getEntity();
try
{
responseBody = EntityUtils.toString( entity );
}
catch ( Exception e )
{
LOG.error( "Unable to parse response", e );
e.printStackTrace();
}
Where response is a org.apache.http.HttpResponse type object.
After converting into a string, the response looks like :
["abc","bcd","cde"]
Now, I was trying to put this into jsonObject or JsonArray as
JSONArray jsonArray = new JSONArray(responseBody);
Arrays.asList(jsonArray).stream().forEach(e-> LOG.info("Connector: " + e));
While my jsonArray looks good, getting error like :
["abc","bcd","cde"] is not an array
Question is : How to convert that jsonArray into a List in Java ?
I assume JSONArray comes from Android. You can just do this:
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
Source: Convert Json Array to normal Java list
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to write a value fetched from a hashmap into a file :
public writeToFile(HapshMap<String,String> , String fileName) {
File myFile = new File(filePath);
BufferedWriter bufferedWriter = null;
Writer writer = new FileWriter(myFile,false);
bufferedWriter = new BufferedWriter(writer);
String paramsValue = params.get("NAME");
bufferedWriter.write(paramsValue);
}
In the above code , the key "NAME" is not there in the HashMap.
And it is throwing NPE .Can anyone suggest what can be done and why is NPE getting thrown?
BufferedWriter does throw an NPE when you ask it to write null somewhere.
That is a situation you will have to know about and deal with. For example, replace null value with some well known string that indicates emptiness:
Object nvl(Object value, Object defaultValue) {
return value != null ? value : defaultValue;
}
<...>
String value = nvl(map.get("Name"), ""); // using empty string instead of null
writer.write(value);
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I have the following code:
while (true) {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
String result = null;
while (result != "string") {
out.println("string one");
out.flush();
String var = null;
if ((var = in.readLine()) != null) {
var2 = function(login);
out.println(var2);
out.flush();
}
}
}
The flushing is not working correctly, mainly the first iteration of the outer while loop will print both outputs, but then after that there is an odd delay and everything is messed up ("string one" is not printing to the output).
What am I doing wrong?
You are using != tocompare String references which isn't going to do what you thinks, though it doesn't matter because you never change anyway.
Most likely you have a bug at the other end which is why readLine() blocks waiting for some text.