在JSONObject中发送值列表

时间:2017-03-16 13:10:06

标签: java json

public class sample {
    public static void main(String[] args) {
        List<String> sList = new ArrayList<String>();
        JSONObject inputJsonObj = new JSONObject();
        try {


            inputJsonObj.put("ipaddress","10.254.27.12");

            inputJsonObj.put("ipaddress", "10.253.140.116");


            Client client = Client.create();
            WebResource webResource = client
                    .resource("http://10.85.249.29:8080/checkRest/CheckxARC/getVersion");
//             

            ClientResponse response = webResource.type("application/json")
                    .post(ClientResponse.class, inputJsonObj.toString());
            String output = response.getEntity(String.class);

            System.out.println(" op--->"+output);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

我已经创建了一个用于调用restful webservices的客户端代码。以前当我发送单个ipaddress时,它工作得很好。现在当我尝试发送超过1个IPadrresses时,我能够继续。可以有人建议我如何进行它?

2 个答案:

答案 0 :(得分:0)

你能不能只为该值存储的密钥添加一个整数值?然后在接收端只需编写一些内容循环并获取所有值示例:

  public class sample {
        public static void main(String[] args) {
            List<String> sList = new ArrayList<String>();
            JSONObject inputJsonObj = new JSONObject();
            try {

                inputJsonObj.put("ipaddress","10.254.27.12");
                inputJsonObj.put("ipaddress1", "10.253.140.116"); // Add one to the name

                Client client = Client.create();
                WebResource webResource = client
                        .resource("http://10.85.249.29:8080/checkRest/CheckxARC/getVersion");            

                ClientResponse response = webResource.type("application/json")
                        .post(ClientResponse.class, inputJsonObj.toString());
                String output = response.getEntity(String.class);

                System.out.println(" op--->"+output);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

获取所有IP地址:

    Collection values = jObject.values();
    values.forEach( System.out::print );

代码中编辑错误。

答案 1 :(得分:0)

您可以使用JSONArray。在其中,您将存储所有的IP地址。

然后,使用put方法将数组添加到JSONObject中。

看起来像是:

JSONArray array = new JSONArray();
array.put("10.254.27.12");
array.put("10.254.27.123");

JSONObject inputJsonObj = new JSONObject();
inputJsonObj.put("ipaddresses",array);
// Using ipaddresses as there are many addresses
// The rest of the code stays the same

注意:抱歉,我没有花太多时间来测试它,但逻辑和对象都存在。 :)

干杯