Empty Mysql field (NULL) ends up being a string "null" in Java - java

I have some data extracted from a MySQL database where some fields are NULL. Not accidentally as a string but properly stored as NULL. When I send these null-data JSON-encoded to my android app, they end up being a string "null" of length 4. So I rebuilt this problem condensed to the essential code:
PHP:
$string = null;
echo $array[0]['alt_names'] = $string;
echo json_encode($array);
Java: (My PHP class returns a string, in this case jsonResult)
Log.i("Tag", "result = " + jsonResult); // result = [{"alt_names":null}]
JSONArray jsonArray = new JSONArray(jsonResult);
Log.i("Tag", "jsonArray = " + jsonArray); // jsonArray = [{"alt_names":null}]
JSONObject jsonObject = new JSONObject(jsonArray.getJSONObject(0).toString());
Log.i("Tag", "jsonobject = " + jsonObject); // jsonobject = {"alt_names":null}
String test = jsonObject.get("alt_names").toString();
Log.i("Tag", "test: " + test); // test: null
Log.i("Tag", "test.length(): " + test.length()); // test.length(): 4
The missing quotation marks (not) enclosing null in the Log-output show me, that this is not a string "null" butt actually null. Nevertheless the string's length is 4 and this is true:
if (test.equals("null")) {Log.i("Tag", "true");} // true
What do I not understand? Thanks in advance!

Don't do a toString() on the object return by jsonObject.get("alt_names"). It is actually the static instance of JSONObject.NULL
Object test = jsonObject.get("alt_names");
System.out.println(test == JSONObject.NULL); // true
System.out.println(test.equals(null)); // true
System.out.println(jsonObject.isNull("alt_names")); // true
From javadoc :
It is sometimes more convenient and less ambiguous to have a NULL object than to use Java's null value. JSONObject.NULL.equals(null) returns true. JSONObject.NULL.toString() returns "null".

Related

java: Can't check this string

Can’t convert String into json, and it seems that it will be superfluous for the entire string.
Was thinking maybe json might have helped me out here, but it doesn't seem to give me what I want or I don't know how it will be work.
How I can check the string?
I need to check:
METHOD: GET and URL: http://google.com/
also to check the BODY contains the fields userId, replId and view (no values, only keys)
I was trying to find a way to check that:
if (msg.contains("METHOD: GET") && msg.contains("URL: http://google.com/") && msg.contains("BODY: etc...")) {
System.out.println("ok");
}
It doesn't work. Some values from BODY that are dynamic and that's why for BODY the check won't pass if it’s so hardcoded String. And I guess there're any better ways to do that.
I'd like to have something like:
Assert.assertEquals(
msg,
the expected value for METHOD, which contains GET); // same here for URL: http://google.com/
Assert.assertEquals(
msg,
the expected value for BODY that has userId, replId, and view fields); // or make this assertion for each field separately, such as there is an assertion for the userId field, the same assertions for replId and view
And here's the String:
String msg = "METHOD: GET\n" +
"URL: http://google.com/\n" +
"token: 32Asdd1QQdsdsg$ff\n" +
"code: 200\n" +
"stand: test\n" +
"BODY: {\"userId\":\"11022:7\",\"bdaId\":\"110220\",\"replId\":\"fffDss0400rDF\",\"local\":\"not\",\"ttpm\":\"000\",\"view\":true}";
I can't think of any way to check that. Any ideas?
You can use the java.util.List Interface (of type String) and place the string contents into that list. Then you can use the List#contains() method, for example:
String msg = "METHOD: GET\n" +
"URL: http://google.com/\n" +
"token: 32Asdd1QQdsdsg$ff\n" +
"code: 200\n" +
"stand: test\n" +
"BODY: {\"userId\":\"11022:7\",\"bdaId\":\"110220\",\"replId\":\"fffDss0400rDF\",\"local\":\"not\",\"ttpm\":\"000\",\"view\":true}";
// Split contents of msg into list.
java.util.List<String> list = Arrays.asList(msg.split("\n"));
if (list.contains("METHOD: GET")) {
System.out.println("YUP! Got: --> 'METHOD: GET'");
}
else {
System.out.println("NOPE! Don't have: --> 'METHOD: GET'");
}
I've tried to use Assert:
String[] arr1 = msg.split("\n");
Map<String, String> allFieldsMessage = new HashMap<>();
for (String s : arr1) {
String key = s.trim().split(": ")[0];
String value = s.trim().split(": ")[1];
allFieldsMessage.put(key, value);
}
Assert.assertEquals(
allFieldsMessage.get("METHOD"),
"GET"
);
And the same for URL. But my problem is in BODY part. I thought maybe try to parse this particular part of String into json and then only check the necessary keys.

Use the same method to add elements to ArrayList of String or other object

I, I would like to use the same method to add elements to ArrayList of String or ArrayList of other object. So the ArrayList is of one type but I can pass different arrayList to this method
The problem is the add method, how can I use this method to add String or FleetInfo (my object)?
If I use ArrayList treeFolders I have no error in this method but I can't pass ArrayList
private <T> void addStatisticalFiles (String fleetName, ArrayList<T> treeFolders, boolean isFleetInfo){
String fleetPath = env.getRequiredProperty(PROPERTY_NAME_FILESYSTEM_BASEPATH) + fleetName + File.separator + "statistics";
File statisticalFolder = new File(fleetPath);
if (statisticalFolder != null && statisticalFolder.exists()){
if (!isFleetInfo){
treeFolders.add(fleetPath);
for(String statisticalFile : statisticalFolder.list()){
treeFolders.add(fleetPath + File.separator + statisticalFile);
}
}else{
treeFolders.add(new FleetInfo("dir:" + fleetPath, null, null, null));
for(String statisticalFile : statisticalFolder.list()){
treeFolders.add(new FleetInfo("file:" + fleetPath + File.separator + statisticalFile, null, FleetType.file, null));
}
}
}
}
As generic is compile time decision , compile will not know what kind of object you are going to insert in list , so its just through error as a part of type safety when you add object other then T
Solution 1: I think generic type T has not much required in your case you can do it with nongeneric arraylist as method parameter .
Solution 2 : you need to cast your object to T as below, but in this case you have to make sure your are passing correct class object which is synch with your Boolean parameter.
private void addStatisticalFiles (String fleetName, ArrayList<T> treeFolders, boolean isFleetInfo){
String fleetPath = env.getRequiredProperty(PROPERTY_NAME_FILESYSTEM_BASEPATH) + fleetName + File.separator + "statistics";
File statisticalFolder = new File(fleetPath);
if (statisticalFolder != null && statisticalFolder.exists()){
if (!isFleetInfo){
T t =(T)fleetPath;
treeFolders.add(fleetPath);
for(String statisticalFile : statisticalFolder.list()){
treeFolders.add(fleetPath + File.separator + statisticalFile);
}
}else{
FleetInfo fleetInfo= new FleetInfo("dir:" + fleetPath, null, null, null);
T tfleetInfo =(T)fleetInfo;
treeFolders.add(tfleetInfo );
for(String statisticalFile : statisticalFolder.list()){
treeFolders.add(new FleetInfo("file:" + fleetPath + File.separator + statisticalFile, null, FleetType.file, null));
}
}
}
}

Deserializing Gson NullPointer?

I am trying to parse JSON to get some values.
{
"username":"shobhit#gmail.com",
"roles:
{
"ROLE_Student_Trial":true,
"ROLE_student":true,
"ROLE_Student_Unlimited":true
},
"type":"student",
"lastLogin":1441305986000,
"token":"123"
}
This is how I am deSerializing it
JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();
String userName = obj.get("username").getAsString();
JsonObject roles = obj.get("roles").getAsJsonObject();
Boolean isTrial = roles.get("ROLE_Student_Trial").getAsBoolean();
Boolean isStudent = roles.get("ROLE_Student").getAsBoolean();
Boolean isUnlimited = roles.get("ROLE_Student_Unlimited").getAsBoolean(); // LoginTest.java:31
long lastLogin = obj.get("lastLogin").getAsLong();
int token = obj.get("token").getAsInt();
String type = obj.get("type").getAsString();
System.out.println(userName);
if(isTrial){
System.out.println("Student trial is on last login " + timeConverter(lastLogin));
}
if(isStudent){
System.out.println("Student access level");
}
if(isUnlimited){
System.out.println("Student is unlimited as " + type + " and its token = " + token);
}
I was trying to get values of inner JSON,
but I am getting NullPointerException.
Exception in thread "main" java.lang.NullPointerException
at loginActivityHttpURL.LoginTest.main(LoginTest.java:31)
I am answering to my own question.
JSON is case sensitive, so at ("ROLE_Student") gson wouldn't find any value. Instead I corrected it with ("ROLE_student") and it worked.
Thanks to #Tobia Tesan
Change this line
Boolean isStudent = roles.get("ROLE_Student").getAsBoolean();
to
Boolean isStudent = roles.get("ROLE_student").getAsBoolean();

Request header is returning NULL

I have some issue with the code below, req.getHeader() is returning NULL
// The code below returns the expected value
String header = req.getHeader("x-key");
String size = req.getHeader("x-size");
String contentType = req.getContentType();
logger.info("Content-Length: " + req.getContentLength());
logger.info("x-key : " + header);
logger.info("x-size : " + size);
// The value of req.getHeader below is returning NULL
for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
String headerName = (String) e.nextElement();
logger.info("Name = " + headerName + " " + "Value = " + req.getHeader(headerName ));
}
What could be the problem?
Your code looks OK. If getHeader() returns null the header is indeed null, i.e. was not sent by client.
So, first check your client and be sure it sends the header. Second, try to use network sniffer, e.g. Wireshark and record the network activity.
If you need more assistance please post your client's code.
The below is part of the extract from the api docs.
public java.util.Enumeration getHeaderNames()
Some servlet containers do not allow servlets to access headers using this method, in which case this method returns null

Android Json and null values

How can I detect when a json value is null?
for example: [{"username":null},{"username":"null"}]
The first case represents an unexisting username and the second a user named "null". But if you try to retrieve them both values result in the string "null"
JSONObject json = new JSONObject("{\"hello\":null}");
json.put("bye", JSONObject.NULL);
Log.e("LOG", json.toString());
Log.e("LOG", "hello="+json.getString("hello") + " is null? "
+ (json.getString("hello") == null));
Log.e("LOG", "bye="+json.getString("bye") + " is null? "
+ (json.getString("bye") == null));
The log output is
{"hello":"null","bye":null}
hello=null is null? false
bye=null is null? false
Try with json.isNull( "field-name" ).
Reference: http://developer.android.com/reference/org/json/JSONObject.html#isNull%28java.lang.String%29
Because JSONObject#getString returns a value if the given key exists, it is not null by definition. This is the reason JSONObject.NULL exists: to represent a null JSON value.
json.getString("hello").equals(JSONObject.NULL); // should be false
json.getString("bye").equals(JSONObject.NULL); // should be true
For android it will raise an JSONException if no such mapping exists. So you can't call this method directly.
json.getString("bye")
if you data can be empty(may not exist the key), try
json.optString("bye","callback string");
or
json.optString("bye");
instead.
In your demo code, the
JSONObject json = new JSONObject("{\"hello\":null}");
json.getString("hello");
this you get is String "null" not null.
your shoud use
if(json.isNull("hello")) {
helloStr = null;
} else {
helloStr = json.getString("hello");
}
first check with isNull()....if cant work then try belows
and also you have JSONObject.NULL to check null value...
if ((resultObject.has("username")
&& null != resultObject.getString("username")
&& resultObject.getString("username").trim().length() != 0)
{
//not null
}
and in your case also check resultObject.getString("username").trim().eqauls("null")
If you must parse json first and handle object later, let try this
Parser
Object data = json.get("username");
Handler
if (data instanceof Integer || data instanceof Double || data instanceof Long) {
// handle number ;
} else if (data instanceof String) {
// hanle string;
} else if (data == JSONObject.NULL) {
// hanle null;
}
Here's a helper method I use so that I can get JSON strings with only one line of code:
public String getJsonString(JSONObject jso, String field) {
if(jso.isNull(field))
return null;
else
try {
return jso.getString(field);
}
catch(Exception ex) {
LogHelper.e("model", "Error parsing value");
return null;
}
}
and then something like this:
String mFirstName = getJsonString(jsonObject, "first_name");
would give you your string value or safely set your string variable to null. I use Gson whenever I can to avoid pitfalls like these. It handles null values much better in my opinion.

Categories

Resources