0

In our programming environment at work we have both Java and C# developers. I have a web service I created In C# that the Java developers are trying to consume. I have been writing the Java to consume this web service and while I am getting a json result, it is in the wrong format.

Here is what I have on the c# side:

[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;
}

Then this is the 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());
}

And the response I get is in this form...

{"d":["Sample1","Sample2","Sample3","BD","CN","Name","###","Sample1","Sample2","Sample3","BD","CN","Name","###","Sample1","Sample2","Sample3","BD","CN","Name","###"]}

I was wondering if there was a better way to send the response such that the JSON would look like this:

{"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","###"]}
Shannon Duncan
  • 178
  • 1
  • 12
  • Have you confirmed that the web service works correctly? Have you tried calling it using a C# call for instance? – System Down Sep 24 '13 at 19:39
  • I'm not sure how you want to arrive at your second result - you're only sending a single list with "Sample1", "Sample2", etc... Why should there be four of them? – millimoose Sep 24 '13 at 19:41
  • The `d` is a security feature of .net to prevent the json from being evaluated as javascript: http://stackoverflow.com/questions/6588589/why-do-asp-net-json-web-services-return-the-result-in-d – John Koerner Sep 24 '13 at 19:41
  • Is your C# code actually inside a loop that runs 4 times, maybe with IDs 1, 2, 3, 4? Because otherwise, I have no idea why you're getting the data you are, or would like it in the second form. Why do you have just a bunch of `string`s in a list instead of inside a `DataContract`, with named properties? I'd think that'd be way easier to work with. – Tim S. Sep 24 '13 at 19:42
  • The results are actually be added within a foreach loop. I had to exclude it because it had some sensitive data in it. However I am going to post up an example version of it edited. The webservice itself works correctly. I am just wondering how to send back JSON that will be seen as multiple arrays. If I need to create some other system of storing the results and passing them back that will be fine :). I'm going to edit the post now. – Shannon Duncan Sep 24 '13 at 19:53
  • Edited the original post. – Shannon Duncan Sep 24 '13 at 19:55
  • Try sending a Hashtable instead of a LinkedList. – David Moles Sep 24 '13 at 19:58

1 Answers1

1

Ok I think I see your problem here. You want your data to be serialized as

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

Yet the data structure you are serializing is a single linked list, which is why it is serialized as a single long list. What you need to do is change the data structure. A Dictionary would be perfect, since it is easily serializable as 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;
}
System Down
  • 6,192
  • 1
  • 30
  • 34