【问题标题】:Calling a c# webservice from Java with JSON response使用 JSON 响应从 Java 调用 c# webservice
【发布时间】:2013-09-24 19:35:18
【问题描述】:

在我们工作的编程环境中,我们有 Java 和 C# 开发人员。我有一个用 C# 创建的 Web 服务,Java 开发人员正在尝试使用它。我一直在编写 Java 来使用这个 Web 服务,当我得到一个 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端:

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”等的列表......为什么应该有四个他们?
  • d 是 .net 的一项安全功能,可防止 json 被评估为 javascript:stackoverflow.com/questions/6588589/…
  • 您的 C# 代码实际上是否在一个运行 4 次的循环中,可能 ID 为 1、2、3、4?因为否则,我不知道您为什么要获取数据,或者希望以第二种形式获得数据。为什么列表中只有一堆strings,而不是DataContract,具有命名属性?我认为这会更容易使用。
  • 结果实际上是在 foreach 循环中添加的。我不得不排除它,因为它有一些敏感数据。但是,我将发布一个已编辑的示例版本。 Web 服务本身可以正常工作。我只是想知道如何发回将被视为多个数组的 JSON。如果我需要创建一些其他系统来存储结果并将它们传回,那很好:)。我现在要编辑帖子。

标签: c# java json web-services


【解决方案1】:

好的,我想我在这里看到了您的问题。你希望你的数据被序列化为

{"1":["Sample1","Sample2","Sample3","BD","CN","Name","###"],"2":["Sample1","Sample2","Sample3","BD","CN","Name","###"],"3":["Sample1","Sample2","Sample3","BD","CN","Name","###"] ... etc

然而,您要序列化的数据结构是一个单链表,这就是它被序列化为一个长列表的原因。你需要做的是改变数据结构。 Dictionary 将是完美的,因为它很容易序列化为 JSON。

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public static Dictionary<int,LinkedList<string>> GetInfo(string InfoID, string Username, string Password)
{
    var Result = new Dictionary<int,LinkedList<string>>();
    try
    {
        // Do some stuff I can't show you to get the information...

        foreach (Result from data operations)
        {
            var newList = new LinkedList<string>();     
            newList.AddLast(sample1);
            newList.AddLast(sample2);
            newList.AddLast(sample3);
            newList.AddLast(BD));
            newList.AddLast(CN);
            newList.AddLast(Name);
            newList.AddLast("###");
            int number = something //the number before the list
            Result.add( number, newList);
        }
    }catch(Exception exc)
    {
        .
        .
        .
    }            
    return Result;
}

【讨论】:

  • 真棒这对我需要的东西有用。我只在 c# 中编码了一段时间,对此一无所知!非常感谢!
  • @CodeTheUniverse - 很高兴有帮助:)
猜你喜欢
  • 2011-01-05
  • 1970-01-01
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-07
相关资源
最近更新 更多