5

如何将给定的json包装成字符串并通过android中的Http put请求将其发送到服务器?

这就是我的 json 的样子。

    {
    "version": "1.0.0",
    "datastreams": [
        {
            "id": "example",
            "current_value": "333"
        },
        {
            "id": "key",
            "current_value": "value"
        },
        {
            "id": "datastream",
            "current_value": "1337"
        }
    ]
}

以上是我的 json 数组。

以下是我编写代码的方式,但是它不起作用

        protected String doInBackground(Void... params) {
            String text = null;
            try {
                JSONObject child1 = new JSONObject();
                try{
                    child1.put("id", "LED");
                    child1.put("current_value", "0");


                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


                JSONArray jsonArray = new JSONArray();

                jsonArray.put(child1);

                JSONObject datastreams = new JSONObject();
                datastreams.put("datastreams", jsonArray);  

                JSONObject version = new JSONObject();
                version.put("version", "1.0.0");
                version.put("version", datastreams);


             HttpClient httpClient = new DefaultHttpClient();
             HttpContext localContext = new BasicHttpContext();
             HttpPut put = new HttpPut("url");
             put.addHeader("X-Apikey","");
             StringEntity se = new StringEntity( version.toString());  
             se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

             put.addHeader("Accept", "application/json");
             put.addHeader("Content-type", "application/json");
             put.setEntity(se);


             try{

                   HttpResponse response = httpClient.execute(put, localContext);
                   HttpEntity entity = response.getEntity();
                   text = getASCIIContentFromEntity(entity);
             }
              catch (Exception e) {
                 return e.getLocalizedMessage();
             }


        }catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
            return text;
        }

请帮忙

4

5 回答 5

4

这是一个样本。

    JSONObject Parent = new JSONObject();
    JSONArray array = new JSONArray();

    for (int i = 0 ; i < datastreamList.size() ; i++)
    {
        JSONObject jsonObj = new JSONObject();

        jsonObj.put("id", datastreamList.get(i).GetId());
        jsonObj.put("current_value", datastreamList.get(i).GetCurrentValue());
        array.put(jsonObj);
    }       
    Parent.put("datastreams", array);       
    Parent.put("version", version);

并发送:

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    StringEntity se = new StringEntity( Parent.toString());  
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    post.setHeader("Accept", "application/json");
    post.setHeader("Content-type", "application/json");
    post.setEntity(se);
    client.execute(post);

编辑

在 for 语句中使用的这个示例datastreamList中,是一个列表,对于想要发送到服务器的所有值(一个具有 2 个属性的类的列表, id并且value),实际上我认为您有两个类,如下所示:

class A {

List<Datastreams> datastreamList
String version;
//get
//set
}

class Datastreams {

String id;
String current_value; // or int
//get
//set
}

并且在您的代码中,您必须有一个要发送到服务器的 A 类对象,因此您可以使用第一部分将您objectjson.

于 2014-01-27T09:31:02.790 回答
2

如果您更喜欢使用库,那么我更喜欢您使用Kaush 的Ion Library

形成这个库,您可以像这样简单地发布您的 JSON:

JsonObject json = new JsonObject();
json.addProperty("foo", "bar");

Ion.with(context, "http://example.com/post")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
   @Override
    public void onCompleted(Exception e, JsonObject result) {
        // do stuff with the result or error
    }
});
于 2014-01-28T05:30:38.633 回答
0

只是您必须作为字符串发送,因此将以下 JSON 数据存储在字符串中

{
    "version": "1.0.0",
    "datastreams": [
        {
            "id": "example",
            "current_value": "333"
        },
        {
            "id": "key",
            "current_value": "value"
        },
        {
            "id": "datastream",
            "current_value": "1337"
        }
    ]
}

那么你必须发送如下:

pairs.add(new BasicNameValuePair("data", finalJsonObject.toString()));
于 2014-01-27T09:59:37.283 回答
0

'{' 括号代表一个对象,'[' 代表一个数组或列表。在你的情况下创建一个bean

YourObj{
private String version;
private List<DataStream> datastreams;
//getters
//setters 
}
DataStream{
private String id;
private String current_value;
//getters
//setters
}

使用org.codehaus.jackson:jackson-xcjar 进行 json 解析

使用对象映射器

字符串到对象

 YourObj obj = new ObjectMapper().readValue(stringyouwanttopass,new TypeReference<YourObj>(){});

现在您可以使用解析后的值了。

或者您可以将值设置为YourObj

YourObj obj =new YourObj();
obj.setVersion(1.0.0);
List<Datastream> datastreams=new ArrayList<Datastream>();
Datastream datestr=new Datastream();
datestr.setId("example");
datestr.setCurrent_value("333");
datastreams.add(datestr);
datestr.setId("key");
datestr.setCurrent_value("value");
datastreams.add(datestr);
datestr.setId("datastream");
datestr.setCurrent_value("1337");
datastreams.add(datestr);
JSONObject jsonget = new JSONObject(appObject);
jsonget.toString();

使用 Jersey 连接服务器

Client client = Client.create();
WebResource webResource = client.resource("serverURl");
ClientResponse response = webResource.path("somePath")
                    .type("application/json").accept("application/json")
                    .post(ClientResponse.class, jsonget.toString());

在服务器端将其作为字符串获取并解析。

于 2014-01-28T05:55:03.053 回答
0

这是一个可以帮助您的 android 客户端库:Httpzoid - Android REST (JSON) 客户端,它有一些示例,您可以轻松发布、获取请求。 https://github.com/kodart/Httpzoid

于 2016-01-28T07:30:54.433 回答