protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
Gson gson = new Gson();
LocationTypes locTypes = new LocationTypes();
String json = gson.toJson(locTypes);
out.print(json);
out.flush();
}
If i take the above code, and System.out.println(json), it looks like this :
{"locationTypes":["Hospital","Church","Restaurant","Bar","Other"]}
What i get in the browser, when pointing to the url for the servlet, i get this:
{"calls":{"threadLocalHashCode":-2084311414},"typeTokenCache":{"com.google.gson.InstanceCreator\u003c?\u003e":{},"int":{},"java.lang.String":{},"java.lang.String[]":{},"java.util.Map\u003ccom.google.gson.reflect.TypeToken\u003c?\u003e, com.google.gson.TypeAdapter\u003c?\u003e\u003e":{},"java.util.List\u003ccom.google.gson.TypeAdapterFactory\u003e":{},"java.lang.ThreadLocal\u003cjava.util.Map\u003ccom.google.gson.reflect.TypeToken\u003c?\u003e, com.google.gson.Gson$FutureTypeAdapter\u003c?\u003e\u003e\u003e":{},"com.google.gson.TypeAdapterFactory":{},"com.google.gson.JsonDeserializationContext":{},"com.google.gson.reflect.TypeToken\u003c?\u003e":{},"java.util.Map\u003cjava.lang.reflect.Type, com.google.gson.InstanceCreator\u003c?\u003e\u003e":{},"com.google.gson.Gson":{},"boolean":{},"java.lang.reflect.Type":{},"data.LocationTypes":{},"java.lang.Class\u003c? super ?\u003e":{},"java.lang.Integer":{},"com.google.gson.internal.ConstructorConstructor":{},"com.google.gson.TypeAdapter\u003c?\u003e":{},"com.google.gson.JsonSerializationContext":{}},"factories":[null,null,{"version":-1.0,"modifiers":136,"serializeInnerClasses":true,"requireExpose":false,"serializationStrategies":[],"deserializationStrategies":[]},null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,{"constructorConstructor":{"instanceCreators":{}}},{"constructorConstructor":{"instanceCreators":{}},"complexMapKeySerialization":false},{"constructorConstructor":{"instanceCreators":{}},"fieldNamingPolicy":"IDENTITY","excluder":{"version":-1.0,"modifiers":136,"serializeInnerClasses":true,"requireExpose":false,"serializationStrategies":[],"deserializationStrategies":[]}}],"constructorConstructor":{"instanceCreators":{}},"serializeNulls":false,"htmlSafe":true,"generateNonExecutableJson":false,"prettyPrinting":false}
Update
I have reproduced your error.
Unfortunately, you are passing the gson object to be converted to JSON.
Your problem is the result of a typo/mistake.
I ran the following code:
public static void main (String args[])
{
Gson gson = new Gson();
String json = gson.toJson(gson);
System.out.println(json);
}
And received the following:
{"calls":{"threadLocalHashCode":1253254570},"typeTokenCache":{"com.google.gson.Gson":{},"com.google.gson.reflect.TypeToken\u003c?\u003e":{},"com.google.gson.internal.ConstructorConstructor":{},"com.google.gson.InstanceCreator\u003c?\u003e":{},"java.lang.reflect.Type":{},"boolean":{},"int":{},"com.google.gson.JsonDeserializationContext":{},"com.google.gson.JsonSerializationContext":{},"java.lang.ThreadLocal\u003cjava.util.Map\u003ccom.google.gson.reflect.TypeToken\u003c?\u003e, com.google.gson.Gson$FutureTypeAdapter\u003c?\u003e\u003e\u003e":{},"java.util.List\u003ccom.google.gson.TypeAdapterFactory\u003e":{},"java.util.Map\u003cjava.lang.reflect.Type, com.google.gson.InstanceCreator\u003c?\u003e\u003e":{},"com.google.gson.TypeAdapter\u003c?\u003e":{},"java.lang.Integer":{},"com.google.gson.TypeAdapterFactory":{},"java.lang.Class\u003c? super ?\u003e":{},"java.util.Map\u003ccom.google.gson.reflect.TypeToken\u003c?\u003e, com.google.gson.TypeAdapter\u003c?\u003e\u003e":{}},"factories":[null,null,{"version":-1.0,"modifiers":136,"serializeInnerClasses":true,"requireExpose":false,"serializationStrategies":[],"deserializationStrategies":[]},null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,{"constructorConstructor":{"instanceCreators":{}}},{"constructorConstructor":{"instanceCreators":{}},"complexMapKeySerialization":false},{"constructorConstructor":{"instanceCreators":{}},"fieldNamingPolicy":"IDENTITY","excluder":{"version":-1.0,"modifiers":136,"serializeInnerClasses":true,"requireExpose":false,"serializationStrategies":[],"deserializationStrategies":[]}}],"constructorConstructor":{"instanceCreators":{}},"serializeNulls":false,"htmlSafe":true,"generateNonExecutableJson":false,"prettyPrinting":false}
Kudos to Pragmateek for also checking the GSON SVN repo.
Original Answer
It's really quite impossible that System.out.println(json); would give you a different result than
out.print(json);
out.flush();
json is a String and dispays the same in any stream.
Have you checked that you don't have a typo somewhere?
I would suggest you copy and paste the code exactly as is within your project.
In the browser, you are getting a JSON version of an object that has serialized all the object's values/fields to JSON.
Many of the keys within your generated JSON are actual fields of the object your trying to serialize to JSON as Pragmateek has said.
It could almost be suspected that your are passing your GSON object to be converted to JSON....
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
Gson gson = new Gson();
LocationTypes locTypes = new LocationTypes();
String json = gson.toJson(locTypes);
response.setContentType("application/json");
out.print(json);
out.flush();
}
try setting content-type as above
Is this the original code?
Are you sure there isn't a typo like:
out.print(gson);
Because the strange JSON really looks like a serialized GSON library object...
Related
I want to add JSONArray in spring's model attribute and return from ModelAndView Controller. Not able to do like below. Request for help. Thanking you!
#RequestMapping(value = "/sample.htm", method = RequestMethod.GET)
public ModelAndView seatRequest( ModelMap model,
HttpServletRequest request,HttpServletResponse response, HttpSession session) throws JSONException, JsonProcessingException {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("0", "val0");
jsonObject.put("1", "val1");
jsonObject.put("2", "val2");
jsonArray.put(jsonObject);
model.addAttribute("jsonData",jsonArray.toString());
return new ModelAndView("sample");
What is your intention? Currently JsonArray is added in String form.You can access this jsonArray as a String in your view. But I think you don't want to do that. If you want to access it as object just add as model.addAttribute("jsonData",jsonArray) and then you can access it as object in your views.
Also, In your json Object, Key value is Numric "0","1" so on. make it alphanumeric i.e "key1", "key2" etc. and values "val1","val2" etc. Because name of identifiers cannot start with numbers.
I am working on a project where I need to process JSON string and to test it I write the following code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ParseException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String res=null;
res= "{\"array\":[{\"title\":\"21 new minister join PM narendra modi's gov , shiv sena boycotts oath ceremony\",\"cat\":\"academic\"}]}";
out.print(res);
JSONObject json = new JSONObject(res);
out.print(json);
}catch(Exception e){
e.printStackTrace();
} finally {
out.close();
}
}
I already check the string res at http://pro.jsonlint.com/ and it approved this String.
I also debug the code and set the breakpoint at out.print(res) and it's working fine and then goes to out.close() without throwing any Exception. The debugger message is same as title "json =>json is not a know variable in the current context<"
if you want to pass your json data to the calling area as response then you need to change
out.print(json);
to
out.write(json.toString());
out.flush();
I have created a script on browser that calls a servlet which is deployed on GAE. The servlet uses Datastore.
Everytime servlet is called I receive the following error
Uncaught exception from servlet java.lang.NoClassDefFoundError: org/json/JSONException
For development I use eclipse and Maven.
In pom.xml I have already included org.json 20090211 and javax.validation.
UPDATE
In order to better clarify my question I am posting code from servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = request.getReader();
String str;
while ((str = br.readLine()) != null)
{
sb.append(str);
}
String jsonResp = sb.toString();
JSONParser gparser = new JSONParser();
The problem appears on the last line, so I am posting code from JSONParser
public class JSONParser {
public ArrayList<String> ReturnGoogleJSON(String ResponseString) throws IOException {
ArrayList<String> Row = new ArrayList<String>();
try {
JSONObject rootObject = new JSONObject(ResponseString); // Parse the JSON to a JSONObject
JSONArray rows = rootObject.getJSONArray("items") ; // Get all JSONArray rows
for(int i=0; i < rows.length(); i++) { // Loop over each each row
JSONObject element = rows.getJSONObject(i); // Get the element object
Row.add(element.getString("tag"));
Row.add(element.getString("link"));
Row.add(element.getString("priority"));
}
} catch (JSONException e) {
e.printStackTrace();
}
return Row;
}
}
Could anyone help me with this kind of error?
Thank you in advance.
Check war/WEB-INF/lib directory of your project in eclipse before upload and make sure that json and other dependent files are present in this directory.
Edit:
You may want to check:
GAE - ClassNotFoundException after deployment to Appspot server
http://javanto.com/blog/2012/01/11/gae-eclipse-maven-2-0/
How do I send java string array to sencha touch list. I am using a servlet and gson and I get the error at the line JsonObject creation.
import com.google.gson.JsonObject;
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String[] anArray;
anArray = new String[11]; //assign each element of array later
JsonObject myObj = new JsonObject();
PrintWriter out = response.getWriter();
for(int i = 0; i <11; i++){
myObj.addProperty(anArray[i], i);
}
out.println(myObj.toString());
out.close();
}
eg:-
The following link uses jdbc to serve it via a database.
http://www.mysamplecode.com/2012/05/sencha-touch-list-example.html
Similar to this but the data is to be taken from the array of strings.
Set your content type to application/json on line 4 -
response.setContentType("application/json");
and make sure you are sending properly formatted JSON from your servlet.
I am writing code that needs to extract an object literal posted to a servlet. I have studied the API for the HttpServletRequest object, but it is not clear to me how to get the JSON object out of the request since it is not posted from a form element on a web page.
Any insight is appreciated.
Thanks.
are you looking for this ?
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} finally {
reader.close();
}
System.out.println(sb.toString());
}
This is simple method to get request data from HttpServletRequest
using Java 8 Stream API:
String requestData = request.getReader().lines().collect(Collectors.joining());
make use of the jackson JSON processor
ObjectMapper mapper = new ObjectMapper();
Book book = mapper.readValue(request.getInputStream(),Book.class);
The easiest way is to populate your bean would be from a Reader object, this can be done in a single call:
BufferedReader reader = request.getReader();
Gson gson = new Gson();
MyBean myBean = gson.fromJson(reader, MyBean.class);
There is another way to do it, using org.apache.commons.io.IOUtils to extract the String from the request
String jsonString = IOUtils.toString(request.getInputStream());
Then you can do whatever you want, convert it to JSON or other object with Gson, etc.
JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);
If you're trying to get data out of the request body, the code above works. But, I think you are having the same problem I was..
If the data in the body is in JSON form, and you want it as a Java object, you'll need to parse it yourself, or use a library like google-gson to handle it for you. You should look at the docs and examples at the project's website to know how to use it. It's fairly simple.
Converting the retreived data from the request object to json object is as below using google-gson
Gson gson = new Gson();
ABCClass c1 = gson.fromJson(data, ABCClass.class);
//ABC class is a class whose strcuture matches to the data variable retrieved