简体   繁体   中英

How to convert String to Json

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();

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));

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();

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM