我使用nodejs(expressjs)作为服务器。我有Android应用程序发送json请求到服务器。我有像这样定义的mongoose模式
var mongoose=require('mongoose'),
Schema=mongoose.Schema;
var actSchema= new Schema({
actfees: {type: Number},
actage: {
from: {type: Number},
to: {type: Number}
},
actbatches: [{
days: [String],
starttime: {type: String},
endtime: {type: String}
}]
});
传入的请求看起来像这样
{ actId: '28',
actage: '{from=3.0, to=40.0}',
actbatches: '[{days=[Tue, Wed, Thu, Fri], endtime=17:00, starttime=16:00}]',
actdescr: 'Learn 5 different style of swimming',
actfees: '4000'
}
请参阅actage和actbatches参数。它们被视为字符串而不是数组(如果是actbatches)或嵌入对象(如果是年龄)。
我的app.js有以下行
var express = require('express')
, mongoose = require('mongoose').set('debug', true)
, bodyParser = require('body-parser');
var app = express();
// all environments
app.set('port', process.env.PORT || 8080);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
//客户端代码
BEAN Classes:
public class ActBean {
private String actfees;
private ActAgeBean actage;
private ArrayList<String> days;
getters & setters....
}
public class ActAgeBean {
private int from;
private int to;
//getters & setters...
}
Android应用程序类:
private void Save(ActBean actbean)
{
Type type = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> actMap = new Gson().fromJson(new Gson().toJson(actbean), type);
post(url, actMap);
}
帖子方法:
public String post(String url, Map<String, Object> data) throws Exception {
HttpPost request = new HttpPost(url);
List<NameValuePair> nameValuePairs = setParams(data);
try {
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode > 300){
throw new Exception("Error executing POST request! Received error code: " + response.getStatusLine().getStatusCode());
}
//return new JSONObject(readInput(response.getEntity().getContent()));
return readInput(response.getEntity().getContent());
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
setParams:
private List<NameValuePair> setParams(Map<String, Object> data){
List<NameValuePair> nameValuePairs = null;
if (data != null && !data.isEmpty()) {
nameValuePairs = new ArrayList<NameValuePair>(2);
Iterator<String> it = data.keySet().iterator();
while (it.hasNext()) {
String name = it.next();
Object value = data.get(name);
nameValuePairs.add(new BasicNameValuePair(name, value.toString()));
}
}
return nameValuePairs;
}
请建议我如何确保req.body正确识别数组和嵌入对象。