convert map of custom object to json object? - javascript

In java , i have a hashmap like below
Map<String, List<Employee>> = new HashMap<String, List<Employee>>();
I need to convert the above map to json object
What I tried:-
used jsonObject instead of HashMap and JsonArray instead of list
com.amazonaws.util.json.JSONObject jsonObject = new com.amazonaws.util.json.JSONObject();
com.amazonaws.util.json.JsonArray empList = new JsonArray();
empList.add(empObject)
jsonObject.put("some String", empList);
Then add jsonObject in request attribute
request.setAttribute("empMap", jsonObject.toString() );
but when i retrieve it in javascript i get the value of jsonObject
{emp_10:[com.val.Emp#4b7b4bc5]}
As you can see above i get the value com.val.Emp#4b7b4bc5 not its properties why so ?
Also Is there a better way where i can convert the hashmap of custom object i.e Map<String, List<Employee>> to json object without using
jsonObject instead of HashMap and JsonArray instead of list?
I am using already below libraries in my project and open to use any new one if required
Jettison Library (org.codehaus.jettison.json.JSONObject)
json-lib(net.sf.json.JSONObject)
apache json library (com.amazonaws.util.json.JSONObject)

I think you need to have an additional helper function at java end
public JSONObject asJSON(Employee employee) {
ObjectMapper mapper = new ObjectMapper();
return new JSONObject(mapper.writeValueAsString(employee));
}
and in place of adding empObject in following, add the updated value asJSON(empObject)
empList.add(empObject)
Additionally, remove .toString()
request.setAttribute("empMap", jsonObject.toString());

Related

How to retrieve value from json of one array and one int literal in javascript

I am passing data back to java script through a rest api. The rest API return data in the following below mentioned structure.I am confused what format of json is it and how can i iterate on the array inside and get the int value individually.
The format of my response is like :
{"searchOrder":[
{"location":"10","trackingId":"656"},
{"location":"34","trackingId":"324"},....],
"count":100}
i want searchOrder as array of json to display in table and count to show total row.How can i get them?
Just iterate over the array and extract the values
// Turn the JSON into a JS object (maybe in your XHR handler)
var data = JSON.parse(jsonString); // jsonString could be responseText from XHR
var arrayOfTrackingIdValues = data.searchOrder.map(function (value) {
return value.trackingId;
});
JavaScript provide built-in function JSON.parse() to convert the string into a JavaScript object and drive/iterate the each element based on type obj/array
var obj = JSON.parse(text);

Hashmap of hashmaps converted to json in java. When sent to jsp, i parsed it in javascript. But it is not parsed correct in javascript

In java
HashMap<String, HashMap<String, String>> modFieldHash = new HashMap<String,HashMap<String, String>>();
JSONObject modFieldJson = new JSONObject(modFieldHash);
request.setAttribute("hash",modFieldJson);
In jsp,
JSONObject modFieldHash = (JSONObject)request.getAttribute("hash");
In javascript,
var modField = JSON.parse(<%=modFieldHash%>);
is my code. If hashmap is <"chk",<"chk1","chk1">>, then it is received as
{"chk","{chk1=chk1}"} in js.
JSON.parse wont work on the second hashmap.
For nested hash maps you will get better JSON rendering with the GSON library.
Use it in java as follows:
HashMap<String, HashMap<String, String>> modFieldHash =
new HashMap<String,HashMap<String, String>>();
Gson gson = new Gson();
request.setAttribute("hash", gson.toJson(modFieldHash));

Convert String to JSON object in GWT (JSNI)

How to convert a string to a JSON object that I'll use inside JSNI?
Thank you.
This is a copy-paste way to do it:
import com.google.gwt.core.client.JsonUtils;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
...
JSONObject data = new JSONObject(JsonUtils.safeEval(jsonString));
JSONArray array = data.get("anArray").isArray();
JSONObject obj = data.get("anObject").isObject();
You should look at gwt core JsonUtils which has a safeEval method for the string. You should define a JavaScript Overlay Object for use with the result or you could work with the object in JSNI as you seem to want to.

Escaping the whole object array with JQuery

Can I escape array of object with Jquery ? I got error SyntaxError: illegal character when I retrieving Java.Util.List object. At my Controller class , I pass object array as like that..
Map<String, List<User>> result = new HashMap<String, List<User>>();
// getting datas from database
List<User> datas = new ArrayList<User>();
datas = dao.get...................
result.put("data",datas);
When I gettting it from my JSP as
<script type="text/javascript">var results = ${result.data};</script>
I got syntaxError.So, I googling it and I assume my object array contains illegal characters and I should escape them. (This may my opinion ). So , I tried to escape charaters of this object array but I don't know how to do it ? I tried as like these..
console.log(JSON.stringify(${result.data}));
console.log(${result.data}.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));
console.log(${result.data}.replace(/[\u0021-\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u007e]/g, ""));
console.log($.grep( ${result.data}, function(e){ return e.id == id; }));
console.log(JSON.parse(${result.data}));
All produce same error.
Now I am still trouble in it . Any suggestion would be appreciated. My main point to get is I want to use my object array without any error.Please help me.
What ${result.data} does is basically output datas.toString(). It depends on the structure of the User object what the output will be.
The best thing to do is using a Java Objects to JSON serializer like Gson or Jackson and write a Servlet to output the data as JSON.
Gson
Gson gson = new Gson();
String json = gson.toJson(datas);
See Gson user guide.
Jackson
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(datas);
See Jackson documentation.
Servlet
In your Servlet you can output the generated JSON with the correct content type:
response.setContentType("application/json; charset=UTF-8");
try (OutputStream os = response.getOutputStream())
{
os.write(json.getBytes());
os.flush();
}
This way you can simply load your data using jQuery.getJSON().
Now I am fine with that..
<c:set var="results" value="${result.data}" />
<script type="text/javascript">
var results = jQuery.makeArray("${results}");
alert(results.length);
alert("${results[0].attributeName}");
</script>

Passing Array from Activity to Javascript

I know there a couple of threads similar to this one but they dont actually answer the above question.
Firts question: is it true that only primitives can be passed? (String, boolean,...)
Second question: if it is so. I have an array of String in my activiy and i need it to fill a html table in my WebView and apparently i need to use Javascript interface to do so. So the question is: How can i do that? Do I need to create a string in my activity, pass it to JS and once there recreate the array?
You could use JSON as format for your data. A simple way would be to use a lib like GSON http://code.google.com/p/google-gson/ which makes it easy to convert your ArrayList with own object-types to Strings.
Send that to your WebView via the Javascript-interface and use JSON.parse(Stringname) in JS to recreate your Array.
Best wishes,
Tim
Your option is to expose the method using strings and then you can use the JSONObject or JSONArray to parse the string and use it accordingly.
Here is what I did.
#JavascriptInterface
public void passJSON(String array, String jsonObj) throws JSONException
{
JSONArray myArray = new JSONArray(array);
JSONObject myObj = new JSONObject(jsonObj);
...
}
where array is '["string1","string2"]' and jsonObj is '{attr:1, attr2:"myName"}'
"Do I need to create a string in my activity, pass it to JS and once there recreate the array?"
That's the way i resolved it in my case ; i appended a special character to each item in the list while building up the string and later split it up in JS.
var strings = get.list(); // long string from activity.
var item1 = strings.split("=")[0];
var item2 = strings.split("=")[1];
....
Or you could go for a library

Categories

Resources