开发者

JAXBElement related question

开发者 https://www.devze.com 2023-03-27 16:29 出处:网络
I am getting JSON String data like {\"username\":\"KU\",\"pa开发者_如何转开发ssword\":\"KU\"}.

I am getting JSON String data like

{"username":"KU","pa开发者_如何转开发ssword":"KU"}.

How to convert this string to JAXBElement object.

Please give me answer.


You can use Jackson to unmarshal JSON easily. See the code below for your username and password case above. It outputs the following to the console console showing it has created an instance of the class from the JSON string.

{"username":"KU","password":"KU"} -> Username [KU], Password [KU].

import org.codehaus.jackson.map.ObjectMapper;

public class JaxbTest {
  public static void main(String[] args) throws Throwable {
    String json = "{\"username\":\"KU\",\"password\":\"KU\"}";
    ObjectMapper mapper = new ObjectMapper();
    JavaObject javaObject = mapper.readValue(json, JavaObject.class);

    System.out.println(json + " -> " + javaObject.toString());
  }

  private static class JavaObject {
    private String username;
    private String password;

    public JavaObject() { }

    public String getUsername() {
      return username;
    }

    public void setUsername(String username) {
      this.username = username;
    }

    public String getPassword() {
      return password;
    }

    public void setPassword(String password) {
      this.password = password;
    }

    @Override
    public String toString() {
      return "Username [" + this.username + "], Password [" + this.password + "]";
    }
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消