How to convert String to Json

末鹿安然 提交于 2019-12-29 01:33:06

问题


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

回答1:


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



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



回答3:


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


来源:https://stackoverflow.com/questions/10903758/how-to-convert-string-to-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!