2015-07-10 30 views
0

在寫在ASP .NET下基於REST的Web服務:建立適當的JSON對象在Android的一個ASP .NET Web服務

public class DeviceInfo { 
    public string Model { get; set; } 
    public string Serial { get; set; } 
} 

public class DeviceManagerController : ApiController { 
    ... 
    public string Post([FromBody]DeviceInfo info) { 
     ... 
    } 
} 

這裏是我正在構建Android中的JSON對象:

URL url = new URL (url); 
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); 
    urlConn.setDoInput (true); 
    urlConn.setDoOutput (true); 
    urlConn.setUseCaches (false); 
    urlConn.setRequestProperty("Content-Type","application/json"); 
    urlConn.connect(); 

    // Send POST output. 
    JSONObject jsonParam = new JSONObject(); 
    jsonParam.put("Model", "HP"); 
    jsonParam.put("Serial", "1234"); 

    DataOutputStream printout = new DataOutputStream(urlConn.getOutputStream()); 
    String jsonStr = jsonParam.toString(); 
    String encodedStr = URLEncoder.encode(jsonStr,"UTF-8"); 
    printout.writeChars(encodedStr); 
    printout.flush(); 
    printout.close(); 

該代碼成功調用Web服務。但是,參數(DeviceInfo)爲空。

我甚至試着直接傳遞jsonStr而不是先編碼它們。但是,在這種情況下,雖然參數info不再爲空,但成員ModelSerial仍爲空。

我想知道是否有其他東西,我錯過了。問候。

回答

0

使用OutputStreamWriter代替DataOutputStream需要照顧的問題:

OutputStream os = urlConn.getOutputStream(); 
OutputStreamWriter writer = new OutputStreamWriter(os, "UTF-8"); 
writer.write(jsonStr); 
writer.close(); 
os.close(); 
-1

這將花費你更多的時間和精力,而不是必要的。使用像Gson或Jackson這樣的外部json處理庫。創建數據模型類,使用(JsonProperty註釋)註釋屬性並生成適當的json String。 它可以幫助你使用它們:

http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

When is the @JsonProperty property used and what is it used for?

+0

謝謝您的幫助。但是,您的答案有點誤導。 JSONObject與Android SDK一起提供,因此您不需要使用外部庫。 – Peter

+0

是的,它提供了,但你應該知道這是最糟糕的方式之一。想象一下,你的dto有100個字段,數組,並且你想用這個內置的json處理機制來解析它到你的對象(包含例如hashmaps,arraylist和任何你想要的)。現在想象它的解析器代碼對象。通過使用外部庫(btw Gson是Google開發的庫),它始終只是創建數據模型,註釋和總是單行PARSING。字面上單行會將json字符串轉換爲您的對象。 –

+0

那麼使用這些庫就好比穿着新鞋子,而不是在沒有它們的玻璃上行走。它可能,但對你不好。它很痛。我沒有毫無道理地推薦它。 –