Print ParseObject content - java

perhaps this is a silly question but, I'm trying just to print ALL the content (not just one field) of a ParseObject (Parse platform). But I didn't found anything about that, either the API, forums or here.
toString method it's not overridden inside the API, and there is no "toJsonString" or "toJson" or "getValues" nothing like that.
Any suggestion?
Cheers.

Unfortunately, there is no methods provided by `Parse' to do that. But you can use keySet() method to implement that. It's quick sample to give your direction.
try {
TestParse parseObject = ParseObject.createWithoutData(TestParse.class, "tjkbdde0B1");
JSONObject jsonObject = parseObjectToJson(parseObject);
Log.d("TAG", jsonObject.toString(4));
} catch (ParseException | JSONException e) {
Log.e("TAG", e.getMessage());
}
Method to convert to JSON object
private JSONObject parseObjectToJson(ParseObject parseObject) throws ParseException, JSONException {
JSONObject jsonObject = new JSONObject();
parseObject.fetchIfNeeded();
Set<String> keys = parseObject.keySet();
for (String key : keys) {
Object objectValue = parseObject.get(key);
if (objectValue instanceof ParseObject) {
jsonObject.put(key, parseObjectToJson(parseObject.getParseObject(key)));
// keep in mind about "pointer" to it self, will gain stackoverlow
} else if (objectValue instanceof ParseRelation) {
// handle relation
} else {
jsonObject.put(key, objectValue.toString());
}
}
return jsonObject;
}
You can extend it to care about other possible types at Parse, all in your hands.

Is this what you're looking for?
myParseObject.getJSONObject(myKey).toString();
ParseObject getJSONObject method
JSONObject toString method

From ParseObject, you'll have to get each field individually. Depending on the datatype, use something like myParseObject.getString("myStringFieldName") or myParseObject.getInt("myIntFieldName"). Then, once you have that value, you can do whatever you like with it.

https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Object.html#toJSON
Example:
console.log( feature.toJSON() );

Related

How check if an Attribute(object) is null in Java

I need specific data for a report, then I gettin all information from a parent object
Object1
It has many attributes, object attributes
Object11, Object12, Object13, attr1, attr2...
The attributes has many attributes too
Object111, Object131, Object132,..
by now I got 5 level data attributes.
When I send information to my report it says, Error: cause:null
object1.getIdObject11().getIdObject111().getDescription;
It trows error because Object111 is null
I tried using
object1.getIdObject11().getIdObject111().getDescription==null?'':object1.getIdObject11().getIdObject111().getDescription;
but it only verify if description is null, and throws the same error
Then I tried to verify Object
if(object1.getIdObject11().getIdObject111() == null) {
var = object1.getIdObject11().getIdObject111().getDescription;
} else {
var = "";
}
But when Object11 is null, it throws same error.
I don't think its a good way doing this for each attribute (have to get like 30 attributes)
if(object1.getIdObject11()!=null) {
if(object1.getIdObject11().getIdObject111()!=null) {
if(object1.getIdObject11().getIdObject111().getIdObject1111()!=null) {
//...
}
}
}
I want to verify if is there a null object and set '' (blank) if it is, with no such a large code(because the gotten params are set inside a report, mixed with letter).
reportline1 = "Area: "+object1.getIdObject11().getIdObject111().getName;
You code breaks Demeter's law. That's why it's better to refactor the design itself.
As a workaround, you can use Optional
var = Optional.ofNullable(object1)
.map(o -> o.getIdObject11())
.map(o -> o.getIdObject111())
.map(o -> o.getDescription())
.orElse("")
The way I would probably do this to extend the functionality of the code easily in the future might take a bit of writing in the beginning but will be easily usable forever.
I would create a new method in your parent class called hasNull that returns a boolean like so:
public boolean hasNull()
{
boolean hasANull = false;
//Call another hasNull() inside of object11 which in turns calls hasNull() in object111 etc.
//If any of the calls return with a true/null value set hasANull to true
return hasANull;
}
This in turn checks to see if the current objects it contains are null. If one of the class variables is another custom class you created you can then add another hasNull into that one and keep going until you get to the lowest level where you can do a specific operation when the value is null such as set it to "".
After implementing this you will be able to just be able to use it like this any time you need it:
if (!object1.hasNull())
{
//Do whatever you want if there are no null values
}
else
{
//Do whatever you want if there is a null value
}
You can also make this a void method if you only want it to toggle the values on the lowest level, and do not need to do anything in either case.
I prefer the solution that gave dehasi.
But you can also do something like that:
getOrElse(() -> object1.getIdObject11().getIdObject111().getDescription(), "")
Where getOrElse is:
public static <T> T getOrElse(Supplier<T> getter, T elseValue) {
try {
return getter.get();
} catch (Exception e) {
// log or do something with it
}
return elseValue;
}
It may be controversial becaouse you use Exception to do this.
You can use this code to check if your object has a null attribute, the object is myclass;
for (Field f : myclass.getClass().getDeclaredFields()) {
f.setAccessible(true);
try {
if (Objects.isNull(f.get(myclass))) {
isLineContainsNull = true;
}
} catch (Exception e) {
log.error(e.getMessage());
}
}

Flattening a JSONObject in Java - Recursion causing StackOverflowError

I've been writing a method to "flatten" a codehaus JSONObject in Java. Unfortunately, I'm seeing a StackOverflowError in the recursion through the object nests, but I'm finding it difficult to debug. Here is the error I'm seeing:
Exception in thread "main" java.lang.StackOverflowError
at java.util.LinkedHashMap$LinkedHashIterator.<init>(LinkedHashMap.java:345)
at java.util.LinkedHashMap$LinkedHashIterator.<init>(LinkedHashMap.java:345)
at java.util.LinkedHashMap$KeyIterator.<init>(LinkedHashMap.java:383)
at java.util.LinkedHashMap$KeyIterator.<init>(LinkedHashMap.java:383)
at java.util.LinkedHashMap.newKeyIterator(LinkedHashMap.java:396)
at java.util.HashMap$KeySet.iterator(HashMap.java:874)
at org.codehaus.jettison.json.JSONObject.keys(JSONObject.java:533)
at org.codehaus.jettison.json.JSONObject.toString(JSONObject.java:1079)
at org.codehaus.jettison.json.JSONObject.valueToString(JSONObject.java:1210)
I'm using Iterator to loop the keys, and using hasNext() and next() to ensure that I should only be able to access specific object keys.
I started testing with a simple JSONObject of:
JSONObject json = new JSONObject("outer":{"field1":"value","inner":{"field2":12345,"field3":"example#example.com"}});
/*
"outer":{
"field1":"value",
"inner":{
"field2":12345,
"field3":"example#example.com"
}
}
*/
This should result in a single nest containing fields1|2|3.
Here is the code I have so far:
private static JSONObject flatten(JSONObject object, JSONObject flattened){
if(flattened == null){
flattened = new JSONObject();
}
Iterator<?> keys = object.keys();
while(keys.hasNext()){
String key = (String)keys.next();
try {
if(object.get(key) instanceof JSONObject){
flattened.put(key, flatten(object.getJSONObject(key), flattened));
} else {
flattened.put(key, object.get(key));
}
} catch(JSONException e){
System.out.println(e);
}
}
return flattened;
}
I have been debugging this for a while now, but haven't been able to make any headway - so I'd appreciate any pointers with this. Thanks in advance for any help - if any more info is needed, just leave a comment.
Replace
flattened.put(key, flatten(object.getJSONObject(key), flattened));
by
flatten(object.getJSONObject(key), flattened);
Here it gives me {"field1":"value","field2":12345,"field3":"example#example.com"} and I think that's what you want
Notice that when you call the function recursively, you pass the "flattened" object into the function, and then it returns it back to you, which you then add to "flattened". Thus you are adding the object to itself, creating a circular reference
When you do the recursive call, don't add the result back into the object. Just do:
flatten(object.getJSONObject(key), flattened);

check value exist or not in JSON object to avoid JSON exception

I am getting a JSONObject from a webservice call.
JSONObject result = ...........
When i am accessing like result.getString("fieldName");
If the fieldName exist in that JSONObject then it is working fine.If that is not exist i am getting exception JSONObject["fieldName"] not found.
I can use try catch for this.But i have nearly 20 fields like this.Am i need to use 20 try catch blocks for this or is there any alternative for this.Thanks in advance...
There is a method JSONObject#has(key) meant for exactly this purpose. This way you can avoid the exception handling for each field.
if(result.has("fieldName")) {
// It exists, do your stuff
} else {
// It doesn't exist, do nothing
}
Also, you can use the JSONObject#isNull(str) method to check if it is null or not.
if(result.isNull("fieldName")) {
// It doesn't exist, do nothing
} else {
// It exists, do your stuff
}
You can also move the logic to a common method (for code reusability), where you can pass any JSONObject & the field name and the method will return if the field is present or not.
Assuming that you're using org.json.JSONObject, you can use JSONObject#optString(String key, String defaultValue) instead. It will return defaultValue, if key is absent:
String value = obj.optString(fieldName, defaultValueIfNull);
Way better solution is to use optString instead of getString.
String name = jsonObject.optString("fieldName");
// it will return an empty string ("") if the key you specify doesn't exist
Check if your JsonObject implementation contains method called "has". It could be checks if property exist in object.
Many JsonObject implementations contains this method.
I use this code to do so, it returns undefined or a specified defaultValue instead of rising exception
/* ex: getProperty(myObj,'aze.xyz',0) // return myObj.aze.xyz safely
* accepts array for property names:
* getProperty(myObj,['aze','xyz'],{value: null})
*/
function getProperty(obj, props, defaultValue) {
var res, isvoid = function(x){return typeof x === "undefined" || x === null;}
if(!isvoid(obj)){
if(isvoid(props)) props = [];
if(typeof props === "string") props = props.trim().split(".");
if(props.constructor === Array){
res = props.length>1 ? getProperty(obj[props.shift()],props,defaultValue) : obj[props[0]];
}
}
return typeof res === "undefined" ? defaultValue: res;
}

JSONObject when element doesn't exist

I have a struts action receiving following JSON:
{
"commandId":"tC",
"id":"123",
"def":""
}
Following code works just fine:
JSONObject command = null;
String commandId = null;
String deviceId = null;
try {
command = new JSONObject(json);
commandId = command.getString("commandId");
}
Since "def" can be empty, non declared or can contain another array of elements I tried doing this:
JSONObject def = command.getJSONObject("def");
in order to get this JSON object defined in the element def
This only works if def isn't empty like in this example:
{
"commandId":"tC",
"id":"123",
"def":{"1":"aaa", "2":"bbb"}
}
When def is empty or not defined my program stops working on the line JSONObject def = command.getJSONObject("def"); and noticed that it doesn't continue the execution?!
If I put JSONObject def = command.getJSONObject("def"); try / catch block I get _JSONObject["def"] is not a JSONObject _ exception, but execution doesn't continue
How does JSONObject.getJsonObject(String) behave?
I would expect it to return an empty JSONObject and continue the execution.
What I want is to check if there is anything defined in def and then in a if, else decide what to do in my program according to the value found there... I can't find a way to make my program work if a client's json comes with def empty or not defined.
my suggestion is to define "def" either be defined as null or {}:
"def":null or "def":{} to align with its usage agreement
quotes is really just used to indicate the value is a string. following the standard might save you and others from confusion in the future.
Likely it is because it is trying to get a Object and finding a string. In your JSON (if you control it), for an empty object I would do {}. This should allow Java to think it is retrieving an object.
If def is intended to be an object is it not suppose to look like this when empty?
{
"commandId":"tC",
"id":"123",
"def":{}
}
I think having "def":"" will cause the value to be attempted to be parsed as a string value and not an object value.
Maybe this will help someone. I had to solve the same problem. In my case the web service was returning empty JSON objects if it couldn't find the requested record.
Note: the data names have been changed to protect the innocent...
Note 2: this example uses javax.json
import javax.json.*;
JsonObject _jObj = _myRootObj.getJsonObject("someDataNode");
// at this point in execution _jObj could equal {"DataReturn":""}
// or {"DataReturn":"<some valid data>"}
// we want to test the existence of DataReturn before trying to
// use it
JsonValue jv = _jObj.getOrDefault("DataReturn", null);
String js = jv.toString();
// cover all the bases. test the value
if (js == null || js.isEmpty() || js.compareTo("\"\"") == 0)
{
throw new Exception("Error: DataReturn object null. Cannot proceed.");
}
// the object exists, so it's ok to get it
JsonObject jObjDate = _jObj.getJsonObject("DataReturn");
If you're using org.json.JSONObject you can use .isNull(String key) to do this, something like:
if (command.isNull("def") {
// Handle 'def' not being there
} else {
JSONObject def = command.getJSONObject("def");
}

Java - Objective C - for each loop issue

I'm trying to build an application in Android using some codes from Objective-C (IPhone app).I'm trying to understand what exactly is doing a piece of code and translate it into Java code,but I think I need a little help here.So first, here is the Obj-C code :
(BOOL)processSqlInjectQueries:(NSArray *)injectQueries error:(NSError**)error {
//some code
for(NSDictionary * q in injectQueries)
{
if (![q isKindOfClass:[NSDictionary class]]) continue;
StPacketInjectQueryPackage qType = (StPacketInjectQueryPackage)[[q objectForKey:#"type"] intValue];
NSString * query = [q objectForKey:#"query"];
}
//some code
}
In Java, I'm trying to do something like this :
// in some other method :
JSONObject jsonData= new JSONObject();
String authHash = jsonData.getJSONObject("client_auth_hash").toString();
List<Map<String,String>> injectQueries= new ArrayList<Map<String,String>>();
injectQueries.add(new HashMap<String, String>());
//injectQueries.add(authHash);
public boolean processSqlInjectQueries(List<Map<String,String>> injectQueries, Exception error){
if(injectQueries==null || injectQueries.size()==0){
boolean injectsProcessed = this.processSqlInjectQueries(injectQueries,error);
if(!injectsProcessed){
return false;
}
}
Log.i("Info","Processing INJECT Queries...");
boolean res = true;
/*[_dbAdapter beginTransaction];
[_user.userDbAdapter beginTransaction];*/
for(Map<String,String> b : injectQueries){
if(b.getClass().getName()!=injectQueries.getClass().getName()){
continue;
}
//RPCPacketInjectQueryPackage qType = (RPCPacketInjectQueryPackage)
}
return true;
}
But my problem is that is that I get this error : Type mismatch: cannot convert from element type Object to ArrayList.
Any suggestion how to fix that error?
And second question : Can I use Exception error in declaraion of processSqlInjectQueries instead of NSError *error in Obj-C?
Iterating over the ArrayList
The error is being raised because your code needs to declare that b is an Object (since injectQueries contains objects of type Object, not objects of type ArrayList):
for(Object b : injectQueries){
...
}
Since the NSDictionary class in Objective-C closely resembles the Map class in Java, you can mimic the Objective-C code by casting b as a Map, or even better, you can use generics to specify that injectQueries contains Map objects. For example:
public boolean processSqlInjectQueries(List<Map<String,String> injectQueries, Exception error) {
// some code
for(Map<String,String> b : injectQueries) {
...
}
// some code
return true;
}
Exception Handling
As for your second question, methods in Java normally communicate error conditions by throwing Exception objects, so your method signature would resemble the following:
public boolean processSqlInjectQueries(List<Map<String,String> injectQueries) throws Exception
Note that it's always better to be specific with your exceptions (i.e. to throw objects that are subclasses of Exception) so that your method caller has some idea of what went wrong. See the following link for additional guidelines for handling exceptions in Java:
http://www.javapractices.com/home/HomeAction.do#Exceptions
The objective C code is passing through an NSArray containing NSDictionaries through to the method, so the following is probably closer to what you want to do...
public boolean processSqlInjectQueries(List<Map<String,String> injectQueries) {
for(Map<String,String> q : injectQueries) {
// do stuff with q
}
}
To handle the error code, you probably want to think about throwing an exception rather than trying to pass through an "Error" object, so something like the following:
public boolean processSqlInjectQueries(List<Map<String,String> injectQueries) throws Exception {
for(Map<String,String> q : injectQueries) {
// do stuff with q
}
if(errorConditionOccurs) {
throw new Exception();
}
}
You'll want to tailor the exact Exception that's thrown so it matches whatever your code is trying to do.
In response to comment: perhaps this is closer to what you're trying to do?
public boolean processSqlInjectQueries(JSONObject jsonObject) {
for(String key : jsonObject.keys()) {
Object value = jsonOnject.get(key);
// Do stuff with value
}
// Do more stuff
}
And you could call it with:
processSqlInjectQueries(jsonData.getJSONObject("client_auth_hash"));

Categories

Resources