В нашей среде программирования на работе у нас есть как Java, так и разработчики C#. У меня есть веб-служба, которую я создал в C#, которую разработчики Java пытаются использовать. Я пишу Java, чтобы потреблять этот веб-сервис, и пока я получаю json-результат, он находится в неправильном формате.Вызов C# webservice из Java с ответом JSON
Вот что у меня есть на 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 Side:
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","###"]}
Вы подтвердили, что веб-сервис работает правильно? Вы пробовали называть его, например, с помощью вызова 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 –