在我們的編程環境中,我們同時擁有Java和C#開發人員。我有一個在C#中創建的Web開發人員正在嘗試使用的Web服務。我一直在編寫Java來使用這個Web服務,而當我得到一個JSON結果時,它的格式是錯誤的。使用JSON響應從Java調用c#webservice
以下是我對C#的一面:
[WebMethod]
public static LinkedList<string> GetInfo(string InfoID, string Username, string Password)
{
LinkedList<string> Result = new LinkedList<string>();
try
{
// Do some stuff I can't show you to get the information...
foreach (Result from data operations)
{
Result.AddLast(sample1);
Result.AddLast(sample2);
Result.AddLast(sample3);
Result.AddLast(BD));
Result.AddLast(CN);
Result.AddLast(Name);
Result.AddLast("###");
}
}catch(Exception exc)
{
Result.AddLast(exc.ToString());
return Result;
}
return Result;
}
那麼這就是Java方面:
try {
String uri = "http://example.com/service.asmx/GetInfo";
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Setup Connection Properties
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Accept", "application/json");
connection.setChunkedStreamingMode(0);
connection.connect();
// Create the JSON Going out
byte[] parameters = "{'InfoID':'123456789','Username':'usernametoken','Password':'passwordtoken'}".getBytes("UTF-8");
// Start doing stuff
DataOutputStream os = new DataOutputStream(connection.getOutputStream());
os.write(parameters);
os.close();
InputStream response;
// Check for error , if none store response
if(connection.getResponseCode() == 200){response = connection.getInputStream();}
else{response = connection.getErrorStream();}
InputStreamReader isr = new InputStreamReader(response);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(isr);
String read = br.readLine();
while(read != null){
sb.append(read);
read = br.readLine();
}
// Print the String
System.out.println(sb.toString());
// Creat JSON off of String
JSONObject token = new JSONObject(sb.toString());
// print JSON
System.out.println("Tokener: " + token.toString());
response.close();
} catch(IOException exc) {
System.out.println("There was an error creating the HTTP Call: " + exc.toString());
}
而我得到的迴應是這種形式...
{"d":["Sample1","Sample2","Sample3","BD","CN","Name","###","Sample1","Sample2","Sample3","BD","CN","Name","###","Sample1","Sample2","Sample3","BD","CN","Name","###"]}
我想知道是否有更好的方式發送響應,使JSON看起來像這樣:
{"1":["Sample1","Sample2","Sample3","BD","CN","Name","###"],"2":["Sample1","Sample2","Sample3","BD","CN","Name","###"],"3":["Sample1","Sample2","Sample3","BD","CN","Name","###"],"4":["Sample1","Sample2","Sample3","BD","CN","Name","###"]}
您確認Web服務正常工作嗎?您是否嘗試過使用C#調用來調用它? –
我不確定你想如何得到你的第二個結果 - 你只發送一個帶有「Sample1」,「Sample2」等的列表......爲什麼要有四個列表? – millimoose
'd'是.net的安全特性,可以防止json被評估爲javascript:http://stackoverflow.com/questions/6588589/why-do-asp-net-json-web-services-return- the-result-in-d –