如何使用java制作这个json

时间:2015-06-08 11:12:36

标签: java json

我想用java创建这个json,有人帮忙

{
 "comment": "Check out developer.linkedin.com!",
 "content": {
   "title": "LinkedIn Developers Resources",
   "description": "Leverage LinkedIn's APIs to maximize engagement",
   "submitted-url": "https://developer.linkedin.com",  
"submitted-image-url": "https://example.com/logo.png"
 },
 "visibility": {
  "code": "anyone"
}  
}

2 个答案:

答案 0 :(得分:0)

  1. 创建java类以映射到Json ..something like

    public class JavaClass  {
    private String comment;
     // other Can be in map or java class for content
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();
    
     //getters and setters
    }
    
  2. 填充对象并使用任何库转换为Json对象。

     JavaClass  object = new JavaClass ();
     object.set(....)
    
  3. 现在使用JSONbject

     JSONObject jsonObj = new JSONObject( object );
     System.out.println( jsonObj );
    

答案 1 :(得分:0)

try{
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("comment", "Check out developer.linkedin.com!");
        JSONObject contentJsonObject = new JSONObject();
        contentJsonObject.put("title", "LinkedIn Developers Resources");
        contentJsonObject.put("description", "Leverage LinkedIn's APIs to maximize engagement");
        contentJsonObject.put("submitted-url", "https://developer.linkedin.com");
        contentJsonObject.put("submitted-image-url", "https://example.com/logo.png!");
        jsonObject.put("content",contentJsonObject);
        JSONObject visibilityJsonObject = new JSONObject();
        visibilityJsonObject.put("code", "anyone");
        jsonObject.put("visibility",visibilityJsonObject);
    }catch(JSONException ex){
        Log.i("json ex: ",ex.toString());
    }