2012-08-08 45 views
0

我有这样的Java代码解析成JSON在node.js中

DefaultHttpClient httpclient = new DefaultHttpClient();   
     HttpPost httpPostRequest = new HttpPost(URL);   
     StringEntity se;    
     se = new StringEntity(jsonObjSend.toString());   
     // Set HTTP parameters   
     httpPostRequest.setEntity(se);   
     httpPostRequest.setHeader("Accept", "application/json");    
     httpPostRequest.setHeader("Content-type", "application/json");   
     //httpPostRequest.setHeader("Accept-Encoding", "gzip"); 
     // only set this parameter if you would like to use gzip compression    
     long t = System.currentTimeMillis();    
     HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest); 

,这在使用管道写在控制台一切的node.js

var http = require('http'); 
// Configure our HTTP server to respond with Hello World to all requests. 
var server = http.createServer(function (request, response) { 
console.log("Entering"); 


if (request.method === 'POST') { 

    // the body of the POST is JSON payload. 
    request.pipe(process.stdout); 
    } 

}); 

// Listen on port 8000, IP defaults to 127.0.0.1 
server.listen(8000); 

// Put a friendly message on the terminal 
console.log("Server running at http://127.0.0.1:8000/"); 

林,以确保我接收数据。 我真正想要的是将数据解析回JSON,然后将其保存在数组中。 我如何从请求中获取数据? 有没有人有代码示例?

感谢

回答

1
var http = require('http'); 
// Configure our HTTP server to respond with Hello World to all requests. 
var server = http.createServer(function (request, response) { 
console.log("Entering"); 


if (request.method === 'POST') { 

     // the body of the POST is JSON payload. 
     request.pipe(process.stdout); 

     var data = ''; 
     request.on('data', function(chunk) { 
      data += chunk; 
     }); 

     request.on('end', function() { 
      try { 
       data = JSON.parse(data); 
      } catch (e) { 
       console.log(e); 
      } 
     }); 
    } 

}); 

// Listen on port 8000, IP defaults to 127.0.0.1 
server.listen(8000); 

// Put a friendly message on the terminal 
console.log("Server running at http://127.0.0.1:8000/"); 
+0

非常感谢。我不得不行“request.on(‘数据’,功能的最后一个问题(chunk)....“参数'data'是什么意思......它是在什么地方定义的? – user1581164 2012-08-08 11:23:23

+0

'data'和'end'是事件代码。查看本文http://nodejs.org/api/http的.html#http_event_data – 2012-08-08 11:38:12

0

尝试使用下面的概念在你的代码

 response.on('data', function (chunk) 
     { 
       var data = chunk.toString(); 
       var data_val = JSON.parse(data) 
      });