How to convert String to Json

后端 未结 3 739
再見小時候
再見小時候 2020-12-11 12:04

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 v

3条回答
  •  死守一世寂寞
    2020-12-11 12:53

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

提交回复
热议问题