title: Dart - How to receive and decode JSON packet sent from a Java application
body: <p>In my server-side code I need to be able to listen to a socket to exchange JSON 'packets' with a Java 7 test application <em>on the same machine</em>.  The connection is made and a JSON string is constructed and written to the socket by the Java test application.  It is received by the Dart server-side application and passed to a callback method, handleJson, which attempts to decode it.  The process dies on 'JSON.decode'.  </p>
  
  <p>I think it dies because the string is prepended, by the Java 'writeUTF' method with a short int that contains the number of bytes in the JSON UTF-8 uncluding the leading short and the leading byte is 0.</p>
  
  <ol>
  <li>Is there a Dart method to handle this, in each direction, or must I write the code? (I had thought that JSON work easily between languages.)</li>
  </ol>
  
  <p>The JSON string before writing to the socket in my Java test application:</p>
  
  <pre><code>{"target":"DOOR","command":"OPEN"} // 34 characters
  </code></pre>
  
  <p>A Java snippet:</p>
  
  <pre><code>  // in a try-catch 
  Socket client = new Socket(serverName, port);
  OutputStream outToServer = client.getOutputStream();
  DataOutputStream out = new DataOutputStream(outToServer);
  
  out.writeUTF(json);
  
  client.close();
  </code></pre>
  
  <p>The Java documentation states that the out.writeUTF method converts the json string to UTF-8 with the string length prepended as a short int containing the total number of bytes  written.</p>
  
  <p>In main:</p>
  
  <pre><code>ServerSocket.bind('127.0.0.1', 4041)
     .then((serverSocket) {
    print('connected');
        // prints: 'connected'
     serverSocket.listen((socket) {
        socket.transform(UTF8.decoder).listen(handleJson);
     });
  });
  </code></pre>
  
  <p>handleJson method:</p>
  
  <pre><code>handleJson(String stringAsJson){
    print('string length is ' + (stringAsJson.length).toString());
      // prints:  'string length is 36' 
    print('received json $stringAsJson');
      // prints: 'received json '
    String json = JSON.decode(stringAsJson);
      // dies on decode
    print('Sever Socket received: $json');
  </code></pre>
  
  <p>}</p>