简体   繁体   中英

String Object to Json in java

I have a Strig variable. String name = "xyz"; I want to convert it to json object {"name": "xyz"}

I am currently doing it by putting the name in the map and converting map to json.

Map<String, String > map = new HashMap<>();
map.put("name", name);
new Gson().toJson(map);;

Is there better way to do it?

You can use ObjectMapper from com.fasterxml.jackson as

  public static String getString(Object object) {
        try {
            //Object to JSON in String
            return objectMapper.writeValueAsString(object);
        } catch (IOException e) {
            log.error("Exception ", e);
            return "";
        }
    }

You should create an Class Name . So it will automatically create mapping for you:

Sample Code:

public static void main(String[] args) {

    Name name = new Name();
    name.setName("xyz");
    System.out.println(new Gson().toJson(name));
  }

Output: {"name":"xyz"}

Name Class:

public class Name {

  private String name;

  /**
   * @return the name
   */
  public String getName() {
    return name;
  }

  /**
   * @param name
   *          the name to set
   */
  public void setName(String name) {
    this.name = name;
  }

}

If you have a JSON object of any complexity, you should create a POJO to hold it for you as suggested by @notescrew. If this is a one-off (for example, in some Web controllers that return basic status information) and you are on at least Java 9, you can simplify it by using an inline map:

gson.toJson(Map.of("name", name));

Note that most frameworks (client and server) will take care of serializing to JSON for you, so in most cases you can simply pass or return the Map directly.

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