JUnit test shows string not equal when should be equal - java

So, I'm currently doing a JUnit test for saving and loading a save file in JSON format. However, while saving works without a problem, I keep running to an issue where a string I read in from the file is not kept in the variable I'm writing it to.
public void loadSettings(Vector<User> U, String url, String filepath) {
JSONParser parser=new JSONParser();
try {
Object obj=parser.parse(new FileReader(filepath));
JSONObject jsonObject=(JSONObject) obj;
url=jsonObject.get("URL").toString();
//System.out.println(URL);
JSONArray users=(JSONArray)jsonObject.get("Users");
Iterator<Object> iter=users.iterator();
while(iter.hasNext()) {
String temp1=iter.next().toString();
Long temp2=(Long)iter.next();
User n=new User(temp1,temp2.intValue());
U.addElement(n);
}
} catch (Exception e) {
e.printStackTrace();
}
}
The string in question is the "url" string. The values for the User class I have are inserted in fine. I don't know what the problem is, and I've been working on this for hours. Can anyone help?

URL may contains some special characters, you can try like this:
URLEncoder.encode("This string has spaces", "UTF-8");
then store in the file.
last do this:
url = URLDecoder.decode(jsonObject.get("URL").toString(), "UTF-8");

Related

How to fix 'JsonNull cannot be cast to JsonObject'

I call a post API which responds with details on specific addresses, however some of the responses that get returned have no data so they'll be returned as null. How do I stop the casting error in my code?
I currently only get the data as a Json Object and I'm not sure how to rework my code that so when a JsonNull Element gets returned I can handle that data.
JsonElement element = new JsonParser().parse(jsonString);
JsonObject jsonObject = element.getAsJsonObject();
jsonObject = jsonObject.getAsJsonObject("response"); // This is either an object or it is null
String buildName = jsonObject.get("buildingName").getAsString();
String buildNum = jsonObject.get("premisesNumber").getAsString();
String streetName = jsonObject.get("streetName").getAsString();
What I expect to be returned would be either the address details for valid addresses or no information at all for the invalid addresses.
The error that gets produced is this:
java.lang.ClassCastException: com.google.gson.JsonNull cannot be cast to com.google.gson.JsonObject
Before getAsString() check for isJsonNull(). It'll return true if object is Null.
You can rewrite your code as below
String buildName= (jsonObject.get("buildingName").isJsonNull ? null : jsonObject.get("buildingName").getAsString());
Normally is a good idea validate the data is JSON valid
public static boolean isJSONValid(String test) {
try {
new JSONObject(test);
} catch (JSONException ex) {
try {
new JSONArray(test);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
Function above will return you true in case the string is a valid JSON object(could be an object or an array of objects).
After that you can continue parsing using Jackson lib or the GSON lib

Java - '\' not being used to escape double quotes " in string

I have some JSON content in bytebuffer as : {\"ID\":101}"}
This content is being returned from a service invocation. I get result from that microservice in a bytebuffer. (This means - I cannot get the content changed)
Now, I need to get the json object from this buffer. I'm using this code :
ByteBuffer payloadByteBuffer = invokeResult.getPayload();
byte[] payloadByteArray = payloadByteBuffer.array();
rawJson = new String(payloadByteArray, Charset.forName("UTF-8"));
System.out.println("Raw JSon result = "+rawJson);
The string that gets printed is : "{\"ID\":101}"
Please note that '\' is getting printed within the string but it is originally used to escape double quote. So, when I try to convert this string to JSON object, I get an error :
"Missing value at 1 [character 2 line 1]"
which is probably due to '\' not being used to escape double quote character(I think).
So, My question is, how do I modify my string to treat '\' character for it's correct purpose?
I have tried replacing "\". but it didn't work. I don't know why.
I have also tried different charset encoding : US-ASCII and ASCII but got the same result.
You can try json-simple. You can use the dependency from here
P.S: Your JSON response is wrong.
ByteBuffer payloadByteBuffer = invokeResult.getPayload();
byte[] payloadByteArray = payloadByteBuffer.array();
rawJson = new String(payloadByteArray, Charset.forName("UTF-8"));
JSONParser parser = new JSONParser();
try {
JSONObject json = (JSONObject) parser.parse(rawJson);
} catch (ParseException e) {
e.printStackTrace();
}
It parses the JSON with \ in it.
How about using the apache's commons lang library?
I think it's a simple and easy way of remove your problem away.
Here is my full test code for you.
package just.test;
import java.nio.charset.Charset;
import org.apache.commons.lang3.StringEscapeUtils;
import org.json.JSONObject;
import com.ibm.icu.impl.ByteBuffer;
public class UnescapeCharTest {
private static void testJSONString(final String rawJson)
{
JSONObject json = null;
try
{
json = new JSONObject(rawJson);
System.out.println("ID = "+json.get("ID"));
}
catch(org.json.JSONException je)
{
je.printStackTrace();
}
String convJson = rawJson.replace("\\", "");
try
{
json = new JSONObject(convJson);
System.out.println("ID = "+json.get("ID"));
}
catch(org.json.JSONException je)
{
je.printStackTrace();
}
convJson = StringEscapeUtils.unescapeJson(rawJson);
try
{
json = new JSONObject(convJson);
System.out.println("ID = "+json.get("ID"));
}
catch(org.json.JSONException je)
{
je.printStackTrace();
}
}
public static void main(String[] args)
{
String rawJson = "{\\\"ID\\\":101}";
testJSONString(rawJson);
String rawJson2 = null;
ByteBuffer payloadByteBuffer = ByteBuffer.wrap(rawJson.getBytes());
byte[] payloadByteArray = payloadByteBuffer.array();
rawJson2 = new String(payloadByteArray, Charset.forName("UTF-8"));
testJSONString(rawJson2);
}
}
I hope the code is right for you.
Have a good coding...

Java Eclipse - 'Unexpected token END OF FILE at position 0' when trying to read from JSON

I am using Java Eclipse to create an event management system which will write and read JSON files. Here I have code which creates a new JSON file...
public void actionPerformed(ActionEvent arg0) {
//Declaration of variables
String title = txtTitle.getText();
String month = (String) cboMonth.getSelectedItem();
String day = (String) cboDate.getSelectedItem();
String year = (String) cboYear.getSelectedItem();
String location = txtLocation.getText();
String description = txtDescription.getText();
String URL = txtURL.getText();
// Combine multiple variables together to make a single variable
String date = month + "" + day + "" + year;
// Create a new instance of the class called 'Event'
Event event = new Event();
// Assign values to the getter/setter methods of this instance
event.setName(title);
event.setDate(date);
event.setLocation(location);
event.setDesc(description);
event.setURL(URL);
// Add this new instance to the 'eventList' array list
MainMenu.eventList.add(event);
// Create a new instance of the class called 'Event'
JSONObject JSONEvent = new JSONObject();
// Add data to the JSON file
JSONEvent.put("Title", title);
JSONEvent.put("Date", date);
JSONEvent.put("Location", location);
JSONEvent.put("Description", description);
JSONEvent.put("URL", URL);
// Create a new JSON file called 'Events.json' that has elements added to it
try (FileWriter file = new FileWriter("Events.json", true)) {
file.write("\n");
file.write(JSONEvent.toJSONString());
file.flush();
// Error Handling
} catch (IOException e) {
e.printStackTrace();
}
}
This code works perfectly fine by creating a JSON file and populating it with JSONObjects. Here is an image of what a single entry in the JSON file looks like... Single JSON Element
I then have a separate class with the following code which attempts to read the JSON file and output its contents to the console...
public static void main(String[] args) {
JSONObject JSONEvent;
String line = null;
try {
FileReader fileReader = new FileReader("Events.json");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
JSONEvent = (JSONObject) new JSONParser().parse(line);
String title = (String) JSONEvent.get("Title");
System.out.println(title);
String date = (String) JSONEvent.get("Date");
System.out.println(date);
String location = (String) JSONEvent.get("Location");
System.out.println(location);
String description = (String) JSONEvent.get("Description");
System.out.println(description);
String URL = (String) JSONEvent.get("URL");
System.out.println(URL);
Event event = new Event();
event.setName(title);
event.setDate(date);
event.setLocation(location);
event.setDesc(description);
event.setURL(URL);
MainMenu.eventList.add(event);
}
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
When I run this code, I get the following errors in the console...
Unexpected token END OF FILE at position 0
Does anyone have any idea what this error means?
The very first thing you write to the file is an empty line:
file.write("\n");
So, when reading the file, you're trying to parse an empty string to JSON, hence the exception: the parser finds the end of its input before even having a chance to parse anything.
Instead of relying on the internal format of the generated JSON, and to write several distinct JSON objects to the file, it would be simpler, and safer, to write a single array of objects all at once in the file (replacing its previous content), and to read the whole array at once in memory.
Faced a similar issue. Was trying to write a JSON data record from a file on a Kafka topic. Was getting Unexpected token END OF FILE at position . As a fix, I cleared all the \n characters from the file and tried sending it to the kafka topic. It worked.

How to get value from JSON in Android

I have JSON response:
{"error":100,"result":"{\"distance\":2.4,\"duration\":5,\"price\":0}"}
From this response I want to get a "distance" value for example. How to do it?
I tried to do like this:
String distance = String.valueOf(finalResponseDataJOSNObject.getDouble("distance"));
but string value is null. Any ideas?
UPDATE:
Finally we discovered that it was back-end issue and we fixed it. No additional operations like JSONObject conversation to String, special character removal, etc. was necessary.
Simply:
String distance =
String.valueOf(finalResponseDataJOSNObject.getJSONObject("result").getDouble("di‌​stance"));
Try this...
String json = "{\"error\":100,\"result\":{\"distance\":2.4,\"duration\":5,\"price\":0}}";
try {
JSONObject jsonObject = new JSONObject(json);
double distance = jsonObject.getJSONObject("result").getDouble(
"distance");
Log.i("DISTANCE", String.valueOf(distance));
} catch (JSONException e) {
e.printStackTrace();
}
The distance is in a JSONObject under result only. So you have to getJSONObject("result").getDouble("distance").
You can do this in following way:
Remove special character from json string and convert back to json object and process it accordingly:
String json = "{\"error\":100,\"result\":{\"distance\":2.4,\"duration\":5,\"price\":0}}";
try{
JSONObject jsonObject = new JSONObject(json.replaceAll("\"", ""));
JSONObject jsonObject2=jsonObject.getJSONObject("result");
String distance=jsonObject2.getString("distance");
double convertedDistance=Double.valueOf(distance);
Log.i("DistanceInformation", "My Distance from json is="+distance);
}catch(JSONException e)
{
e.printStackTrace();
}
Thanks for you all who responded.
Finally we discovered that it was back-end issue and we fixed it. No additional operations like JSONObject conversation to String, special character removal, etc. was necessary.
Simply:
String distance =
String.valueOf(finalResponseDataJOSNObject.getJSONObject("result").getDouble("di‌​stance"));

Issue with JSON parser for android, which works well for java

I have the following json parsing code which works fine when tested as a java application. But on using it with in an android platform and running , returned the following error
"Unexpected token END OF FILE at position 0"
Here is my code
public boolean parseJSON(String content) {
boolean retvalue=false;
String jsonString=null;
JSONParser parser=new JSONParser();
Object obj;
try {
System.out.println("in the parse json");
obj = parser.parse(content);
JSONArray array=(JSONArray)obj;
JSONObject obj2=(JSONObject)array.get(0);
jsonString=(String) obj2.get("user_id");
System.out.println("in the parse json "+jsonString);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (null != jsonString) {
retvalue = true;
}
return retvalue;
}
The input string for the method is the following
[{"user_id":"1","username":"arvind","password":"somu","firstname":"Arvind somu","accountNumber":"1234567","lastname":"","address":"","email":"sample#gmail.com"}]
I have got the value 1 printed, when tried with java, but no idea why this issue is coming with android. Can body suggest what is wrong with the code.The parser I am using is json-simple1.1.1
Use this:
JSONObject obj2;
obj2 = array.optJSONObject(0);
The method optJSONObject returns a JSONObject and you dont have to cast it, where as get() returns an Object. Try this i think this may solve it.

Categories

Resources