I have an implementation where when user click on checkbox , a json gets associated as value of checkbox and that value is passed to my bean class.
And In the method invoked, the String is then parsed into JSON object.
When I select two checkbox, it works perfectly fine. But if I select one checkbox, then it gives me error.
Here is my Checkbox Bean class -
private ArrayList<String> Ancillary=new ArrayList<String>() ;
public ArrayList<String> getAncillary() {
for(int i=0;i<Ancillary.size();i++){
System.out.println(i+"Object:" +Ancillary.get(i)+"\n\n\n");
}
return Ancillary;
}
public void setAncillary(ArrayList<String> ancillary) {
Ancillary = ancillary;
}
Here is my method where I print value of a Particular key in JSON.
public Event updatePax(RequestContext context) throws Exception {
ExtrasMenu extrasMenu = (ExtrasMenu) context.getConversationScope().get(ScopeKeys.EXTRASMENU);
System.out.println("As a string:"+extrasMenu.getAncillary().toString());
JSONObject json=new JSONObject(extrasMenu.getAncillary().get(0));
System.out.println(json.get("firstName"));
}
And here is the Output-
If only one checkbox is selected -
0Object:{"firstName":"TIMOTHY"
1Object:"lastName":"WALKER"
2Object:"price":100}
If two or more checkboxes are selected -
0Object:{"firstName":"TIMOTHY","lastname":"WALKER","price":"50"}
1Object:{"firstName":"ANNE","lastname":"WALKER","price":"150"}
Since, I couldnt figure out why ArrayList is taking input like this,
I created a special case when User selects one check box. I will take the ArrayList and convert it to a String using toString.
So, the output of toString will be like -
{"firstName":"TIMOTHY","lastname":"WALKER","price":"50"}
Now I used a try catch block to create JSON object out of the string I get from toString.
JSONObject json=null;
try{
json=new JSONObject(extrasMenu.getAncillary().get(i));
}
catch(org.json.JSONException e){
int len=extrasMenu.getAncillary().toString().length();
json=new JSONObject(extrasMenu.getAncillary().toString());
}
So If it throws an error, the full list as a string will be used to create JSON object.
Although It is working fine, Still I am not very sure about Why ArrayList is working like this !
Related
"app":{
"icon":{
"icon":"TOP_RATED"
},
"message":{
"_type":"TextSpan",
"text":"Top Rated"
}
}
I keep seeing the following code in one of the projects that I have inherited. The JSON response above is parsed as follows
// itemObject has the entire json response
// appObject is a POJO with icon, type fields
String icon= JsonPath.with(itemObject).getAsString("icon/icon");
appObject.setIcon(icon);
String type = "";
try {
type = JsonPath.with(itemObject).getAsString("message/_type");
catch(IllegalArgumentException e) {
// do nothing if type is not found in response
} finally {
// set type to empty string if it's not found
appObject.setType(type);
}
In the scenario, when _type doesn't exist for a specific app, would it be best to surround it with a try/catch block as shown above? It just seems wrong to use try/catch/finally block to process business logic instead of error handling. What is a better way to do the same and can Java 8 Optional help with this?
I find the org.json package simple and straightforward. It is found here. The org.json.JSONObject class, for example, contains the public boolean has(String key) method, which is used to check if a certain key exists.
Returns true if this object has a mapping for name. The mapping may be NULL.
You can check this way where 'HAS' - Returns true if this object has a mapping for name. The mapping may be NULL.
if (json.has("status")) {
String status = json.getString("status"));
}
if (json.has("club")) {
String club = json.getString("club"));
}
You can also check using 'isNull' - Returns true if this object has no
mapping for name or if it has a mapping whose value is NULL.
if (!json.isNull("club"))
String club = json.getString("club"));
http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
I tried to set value in TextView using my array logic.
Problem:
Instead of my actual value it might set address of string in
textview. I'm guessing this issue is simple, possibly not specifying .toString()?
Value that is being outputted:
com.android.carModel.Car#eacea24f
My code:
StringBuilder builder = new StringBuilder();
val = carDAO.carOutput(carId);
textbx.setText("");
for (Car details : val){
builder.append(details + "\n");
}
textbx.setText(builder.toString());
Your code is actually append someObjectClassname#hashcodenumber i.e com.android.carModel.Car#eacea24f in your case to stringBuilder. To get the desired output you need to do something like this.
`builder.append(details.getName() /*or anything*/ + "\n")`
Do you have access to the Car class? If so, add this method:
public String toString() {
return carName;
}
Replace carName with whatever you want to display. This toString() method is part of the Object class that all classes extend, and when overridden, it will change what something like a List will display.
The code that we already have return us JsonObject. What I want to do is to add a new key and the value for it.
For example, we have an object like this:
{"id":"12","name":"test"}
I want to transform it into this:
{"id":"12","name":"test","status":"complete"}
I didn't find what I need in documentation except using put method. So I wrote this code:
JsonObject object = getJsonObject();
JsonString val = new JsonString() {
public JsonValue.ValueType getValueType() {
return JsonValue.ValueType.STRING;
}
public String getString() {
return "complete";
}
public CharSequence getChars() {
return (CharSequence) "complete";
}
};
object.put("status", val);
But it doesn't work, crashing with :
java.lang.UnsupportedOperationException
I can't understand what is wrong. Have I any other option to complete such a task?
I don't think JsonObject instances are meant to be modified.
I think your best option is to create a new object, copy the existing properties and add the new property to it.
You can use https://docs.oracle.com/javaee/7/api/javax/json/JsonObjectBuilder.html
Not sure if object.put works but you can use the following way to append the details to JSON value:
You can create a different JSON object with the key and value that you want to add to the JSON object and the user object.merge(status, complete, String::concat);
merge() checks for the key:'status' in your JSON object if it does'nt find it then it adds that key:value pair or else it replaces it
.You are not able to compile it because you may not be using jre 1.8.
I've Just verified the following method:
Just create a new JSONObject(org.json.JSONObject not javax.json.JsonObject)
JSONObject modifiedJsonObject= new JSONObject(object.toString());
modifiedJsonObject.put("status", "complete");
I have a method that takes in a JSON and takes out the data and distributes it to various strings so that they can be set in an entity and persisted. My example below is quite simple but for my actual code I have about 20+ fields
For example see
public Projects createProject(JsonObject jsonInst) {
Projects projectInst = new Projects();
String pId = jsonInst.get("proId").getAsString();
String pName = jsonInst.get("proName").getAsString();
String pStatus = jsonInst.get("proStatus").getAsString();
String pCustId = jsonInst.get("proCustId").getAsString();
String pStartDate = jsonInst.get("proStartDate").getAsString();
...
//Set the entity data
projectInst.setProjectId(pId);
projectInst.setProjectName(pName);
...
Notice if a varible dosent have a corrosponding entry in the Json this code will break with null pointer exception. Obviously I need to validate each parameter befopre calling .getAsString()
What is the best way to do this from a readability point of view I could create 2 varibles for each parameter and check and set for example.
if(jsonInst.get("proName")){
String pName = jsonInst.get("proName").getAsString();
}
Or should I wait for it to be set
if(!pName.isEmpty()){
projectInst.setName(pName)
}
...
Which of these do you think is the best parameter to use for preventing errors.
Is there a way to handle if something is set on a large scale so that I can reduce the amount of code I have to write before I use that varible?
You can create a method that will take field name as parameter and will return json value for that field :
private String getJSONData(String field,JsonObject json){
String data=null;
if(json.has(field)){
data=json.get(field).getAsString();
}
return data;
}
you can call this method for each of your field:
String pId = getJSONData("proId",jsonInst);
By this way you can not only escape NullPointerException, but also avoid code repetition.
Let, say for instance i have a POJO class employee with three attributes
1.Name (String)
2.Location (String)
3.Date of Birth (Date)
then i fired a query into database which retrieve first row of table and populate this POJO
with table data as follows:-
Name - john
location - USA
Date of Birth - 27/09/2014
To retrieve the values from this POJO i have to call getName(),getLocation() and getDOB().
But is there any method by which i can get all the values which is store in the POJO, in an Object type array without using getter method
for example:
Object[0] has the value "John".
Object[1] has the value "USA".
Object[2] has the value "27/09/2014".
(In my case, there are around 80 attributes in a class and number of these attributes increases because of client requirements and i am fetching each and every value by getter method and every time a single attribute is added i have to write a getter method in the code to fetch values. I basically want a more dynamic solution to this problem.)
you can try this:
String[] getObjectsPublicMethods(Object o)
{
Class clazz = o.getClass();
Method[] methods = clazz.getDeclaredMethods();
String[] result = new String[methods.length];
for (int i=0; i<methods.length; ++i)
{
try
{
result[i] = (String) methods[i].invoke(o, new Object[] {})
} catch (IllegalAccessException e)
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InvocationTargetException e)
{
}
}
return result;
}
This method uses reflection to get the information you want, BUT
it assumes that the getter methods are declared public in this class AND
that all of the public methods return String.
I think what you are looking for is called reflection.
i hope this link helps http://docs.oracle.com/javase/tutorial/reflect/index.html
or this answer:
Is it possible to use Java Reflection to print out attributes of the parent class?