2

以下是我在对 Http API 格式发出 get 请求后得到的 Json 响应,

[{"name":"test","tracing":false},{"name":"dyn1","tracing":false},
{"name":"dyn2","tracing":false},{"name":"esb","tracing":false}]

您能否发布一个示例代码来解析此 json 对象以获取具有名称和跟踪的单个 Host 对象。

谢谢,

阿莫尔

4

2 回答 2

1
String myDataAsAString = "[{\"name\":\"test\",\"tracing\":false},{\"name\":\"dyn1\",\"tracing\":false},
{\"name\":\"dyn2\",\"tracing\":false},{\"name\":\"esb\",\"tracing\":false}]";


JSONArray hostArray = JSONArray.fromObject(myDataAsAString);

for(int i = 0; i < hostArray.size(); i++)
{
    JSONObject hostObject = hostArray.getJSONObject(i);
    String hostName = hostObject.getString("name");
    boolean tracing = hostObject.getBoolean("tracing");
    ...your code for each element here
}
于 2013-03-04T22:16:14.103 回答
-1

您可以使用 GSON 库http://code.google.com/p/google-gson/

尝试:

import com.google.gson.Gson;


public class Test {

  public static void main(String[] args){
    String json = "[{'name':'test','tracing':false},{'name':'dyn1','tracing':false},\n" +
            "{'name':'dyn2','tracing':false},{'name':'esb','tracing':false}]";
    HostObj[] hostObjects = new Gson().fromJson(json, HostObj[].class);
  }


  class HostObj {

    private String name;
    private boolean tracing;

    HostObj() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        name = name;
    }

    public boolean isTracing() {
        return tracing;
    }

    public void setTracing(boolean tracing) {
        tracing = tracing;
    }
  }
}
于 2013-03-04T22:41:07.537 回答