1

I have a servlet in Java and I would like to know how I can do the following.

I have a String variable with the value of a name and want to create a Json with the variable being something like {"name": "David"}.

How do I do this?

I have the following code but I get an error :

   Serious: Servlet.service () for servlet threw 
   exception servlet.UsuarioServlet java.lang.NullPointerException 
               at servlet.UsuarioServlet.doPost (UsuarioServlet.java: 166):

at line

String myString = new JSONObject().put("name", "Hello, World!").toString();

3 Answers 3

3

Your exact problem is described by Chandra. And you may use the JSONObject using his suggestion. As you now see, its designers hadn't in mind the properties, like chaining, which made the success of other languages or libs.

I'd suggest you use the very good Google Gson one. It makes both decoding and encoding very easy :

The idea is that you may define your class for example as :

public class MyClass {
   public String name = "Hello, World!";
}

private Gson gson = new GsonBuilder().create();
PrintWriter writer = httpServletResponse.getWriter();
writer.write( gson.toJson(yourObject));
0
2

The json library based on Map. So, put basically returns the previous value associated with this key, which is null, so null pointer exception.( http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html#put%28java.lang.Object,%20java.lang.Object%29)

You can rewrite the code as follows to resolve the issue.

JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("name", "Hello, World");
String myString = jsonObject1.toString();
1
  • I upvote you because you answer more directly than me to the exact encountered bug. Jun 6, 2012 at 6:05
2

I tried with GSON, GSON is directly convert your JSONString to java class object.

Example:

String jsonString = {"phoneNumber": "8888888888"}

create a new class:

class Phone {

@SerializedName("phoneNumber")
private String phoneNumebr;


public void setPhoneNumber(String phoneNumebr) {
this.phoneNumebr = phoneNumebr;
}

public String getPhoneNumebr(){
return phoneNumber;
}

}

// in java

Gson gson = new Gson();
Phone phone = gson.fromJson(jsonString, Phone.class);

System.out.println(" Phone number is "+phone.getPhoneNumebr());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.