簡體   English   中英

您如何編碼以下Json對象?

[英]How do you code the following Json object?

我想創建一個Json對象,如下所示:

{"name": "Maximum", "children": [
                    {"name": "where", "size": 299},
                    {"name": "xor", "size": 354},
                    {"name": "_", "size": 264}
                    ]
}

使用哪個庫來創建上述Json字符串,代碼應如何顯示?

嘗試gson 它對此有很好的支持。 查閱本用戶指南

您的類結構如下所示:

class Parent{
        String name;
        Children[] children;
//getter and setter
    }
    class Children{
        String name;
        int size;
//getter and setter
    }

然后在您的代碼中:

   Parent parent = new Parent();
    //poppulate parent object with required values 
    Gson gson = new Gson();
    gson.toJson(parent);

嘗試使用XStream Json Parser。 我用過了。

http://x-stream.github.io/json-tutorial.html

這是簡單的javascript。

var obj = {"name": "Maximum"};
var children = [];
children.push({"name":"where", "size": 299});
obj["children"] = children;

使用拋棄,您可以執行以下操作:

import java.util.ArrayList;
import java.util.List;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;


public class JSONTest {

  public static void main(final String[] args) throws JSONException {
    final JSONObject jsonObject = new JSONObject();
    jsonObject.put("name", "Maximum");

    final List<JSONObject> children = new ArrayList<JSONObject>();

    final JSONObject child1 = new JSONObject();
    child1.put("name", "where");
    child1.put("size", 299);
    children.add(child1);

    final JSONObject child2 = new JSONObject();
    child2.put("name", "xor");
    child2.put("size", 354);
    children.add(child2);

    final JSONObject child3 = new JSONObject();
    child3.put("name", "_");
    child3.put("size", 264);
    children.add(child3);

    jsonObject.put("children", children);
    System.out.println(jsonObject.toString());

  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM