我正在使用REST API从Mongo DB使用@Form param获取数据并获得异常:'ObjectId的十六进制表示无效'。语法似乎是正确的,不确定那里出了什么问题。我在rest参数中传递新的ObjectId(id)。代码如下:
//Country.java
package com.speed.infoaxon;
import java.io.IOException;
import java.net.UnknownHostException;
import org.bson.types.ObjectId;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
public class Country {
public BasicDBObject addDemo(long _id ) throws IOException {
DB db=ConnectToDB.getConnection();
DBCollection collection = db.getCollection("demo");
BasicDBObject buildList = null;
BasicDBObject document = new BasicDBObject();
document.put("_id",new ObjectId("id"));
collection.save(document);
return buildList;
}
}
//getResponse.java
package com.speed.infoaxon;
import java.io.IOException;
import java.net.UnknownHostException;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
@Path("/add")
public class GetResponse {
@POST
@Path("/addDemo")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED} )
public BasicDBObject addDemo(@FormParam("_id") long _id) throws IOException
{
System.out.println("inside demo");
Country d = new Country();
BasicDBObject basicDBList=d.addDemo(_id);
return basicDBList;
}
}
Please let me know where is the issue. Thanks in advance.
答案 0 :(得分:2)
document.put(“ _ id”,new ObjectId(“ id”));
您在引号中使用“ id”,这意味着您需要以实际ID传递字符串中的ID。