Creating GSON Object

前端 未结 2 488
长情又很酷
长情又很酷 2021-02-01 01:28

How do I create a json Object using Google Gson? The following code creates a json object which looks like {\"name\":\"john\"}

JsonObject jsonObject         


        
相关标签:
2条回答
  • 2021-02-01 01:58

    Figured it out how to do it correctly using Java Objects.

    Creator creator = new Creator("John");
    new Gson().toJson(creator);
    

    Implementation of Creator java class.

    public class Creator {
    
        protected String name;
    
        protected HashMap<String, String> publisher = new HashMap<String, String>();
    
        public Creator(String name){
                publisher.put("name", name);
        }
    }
    
    0 讨论(0)
  • 2021-02-01 02:04
    JsonObject innerObject = new JsonObject();
    innerObject.addProperty("name", "john");
    
    JsonObject jsonObject = new JsonObject();
    jsonObject.add("publisher", innerObject);
    

    http://www.javadoc.io/doc/com.google.code.gson/gson


    Just an FYI: Gson is really made for converting Java objects to/from JSON. If this is the main way you're using Gson, I think you're missing the point.

    0 讨论(0)
提交回复
热议问题