简体   繁体   English

在Java中将ObjectID(Mongodb)转换为String

[英]Convert ObjectID (Mongodb) to String in java

I work on my records that comes from a PHP API , that returns my MongoDB documents as JSON (json_enoded). 我处理来自PHP API的记录,该记录将MongoDB文档以JSON(json_enoded)的形式返回。

all I want is a simple function that gets the actual id from MongoId , like this : 我想要的是一个简单的函数,可从MongoId获取实际的ID,如下所示:

This is the record that comes from API into my java application : 这是从API到我的Java应用程序的记录:

 String id =    cat.getString("_id");
 String id =   "{\"$id\":\"54f76bb7404f9990010041b2\"}"

and cat is a JsonObject that I get from my records; cat是我从记录中获得的JsonObject;

and by the way , I get my records from an API that is written in PHP and all the responses from this API are json_encoded , So they are Strings actually . 顺便说一下,我从用PHP编写的API获取记录,并且该API的所有响应均经过json_encoded编码,因此它们实际上是字符串

I want this : 我要这个 :

 String id =   54f76bb7404f9990010041b2 

is there any easy way ? 有什么简单的方法吗?

EDIT : I'm not using JAva mongo driver , this documents are strings that comes from an Api. 编辑:我不使用JAva mongo驱动程序,此文档是来自Api的字符串。

How about String.split(":") and then a substring from first index of " to last index? Sorry for describing in brief. I can provide a code example, if required. 那么从String.split(":") ,然后是从“”的第一个索引到最后一个索引的substring呢?很抱歉,简短地描述一下。如果需要,我可以提供一个代码示例。

String id = "{'$id':'54f76bb7404f9990010041b2'}";
String[] tokens = id.split(":");
String valueToken = tokens[1];
valueToken = valueToken.substring(1,valueToken.lastIndexOf("'"));
System.out.println(valueToken);

I used @Aminda's answer and used this : 我用@Aminda的答案,并使用了这个:

 String mongo_id = "{\"$id\":\"54f76bb7404f9990010041b2\"}"

 String MongoIdToString(String mongo_id){
    return mongo_id.split(":")[1].substring(mongo_id.indexOf("\"")).split("\"")[0];
}

  String mongo_id = MongoIdToString(mongo_id);

this will produce : 这将产生:

  mongo_id =  54f76bb7404f9990010041b2

Thanks to all; 谢谢大家;

Do something like (assuming your string is: "{_id:....}" : 做类似的事情(假设您的字符串是: "{_id:....}"

String s = yourId.split["::][1];
String id = s.subString(0, s.length - 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM