【问题标题】:How to make this json using java如何使用java制作这个json
【发布时间】:2015-08-22 19:56:53
【问题描述】:

我想用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"
}  
}

【问题讨论】:

  • 您能详细说明一下吗?另外,请向我们展示您迄今为止所做的尝试。这个问题的一个基本答案是 - 根据 JSON 结构创建 Java 对象并使用 JSON-Java(反之亦然)转换库(例如 GSON)。
  • 你试过了吗?可以发一下吗?
  • 我建议谷歌一下如何使用 FasterXML 的 Jackson 数据映射器

标签: java json


【解决方案1】:
  1. 创建java类以映射到Json..类似

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

【讨论】:

    【解决方案2】:
    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());
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多