2014-01-27 164 views
5

如何將給定的JSON包裝到字符串並通過Http把請求發送到服務器android?發送JSON到服務器通過HTTP放置請求在android

這就是我的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; 
     } 

請在此

+0

使用gson,它將幫助你包裝解開你的jsons和對象 – Hardik4560

+0

SO不是'給我teh codez !! 1'網站。請提供您迄今爲止所嘗試的內容。如果你沒有做任何事情,請至少嘗試谷歌和** **然後如果你仍然不能管理 - 在這裏問 –

+0

一般,給JSON來string_ _TO包裝只是把它放到引號和逃避內部引號。 「{」\「version \」:\「1.0.0 \」, \「datastreams \」:[ \「id \」:\「example \」, \「current_value \」:\「333 \」 }, { \ 「ID \」:\ 「鍵\」, \ 「current_value \」:\ 「值\」 }, { \ 「ID \」:\ 「數據流\」, \「current_value \」:\「1337 \」 } ] }「 - 您需要打開一個文本編輯器窗口,並將所有的」-s替換爲\「 - s – 18446744073709551615

回答

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

編輯

此示例 datastreamList是用於在聲明中

是,你必須爲想要發送到服務器的所有值列表(一個類有兩個屬性,idvalue)的列表,其實我認爲你有兩個類似波紋管:

class A { 

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

class Datastreams { 

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

,並在你的代碼,你必須有一個要發送到服務器A類的一個對象,所以你可以先用一部分來映射你的objectjson

+0

但是,如何爲特定的「id」寫「current_value」?恩。 「current_value」=「0」 – user3145687

+0

我不明白你,你能解釋得更清楚嗎? –

+0

「current_value」是我們可以更新像1,2,3或任何字符的數據。那麼,我應該如何將實際數據寫入上述代碼? – user3145687

0

只要你有這樣的字符串以下JSON數據存儲派爲String

{ 
    "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())); 
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 
    } 
}); 
+4

離子是如何用來發送PUT請求?這個例子會發送一個POST請求 – honnix

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-xc罐子JSON parssing

使用ObjectMapper

字符串對象

現在你可以使用分析得到的值。

,或者您可以使用新澤西

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

在服務器端把它作爲串並分析其設置的值到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(); 

連接服務器。

0

這裏是一個android客戶端程序庫可以幫助您: Httpzoid - Android REST(JSON)客戶端,它有一些例子,您可以輕鬆地發佈帖子,獲取請求。 https://github.com/kodart/Httpzoid

+0

只有鏈接的答案在這裏是非常不鼓勵的,因爲鏈接將來可能會死亡。我建議你用引用來源的引文編輯你的答案。 –

+0

比你的建議 –

相關問題