I work on my records that comes from a PHP API , that returns my MongoDB documents as JSON (json_enoded).
all I want is a simple function that gets the actual id from MongoId , like this :
This is the record that comes from API into my java application :
String id = cat.getString("_id");
String id = "{\"$id\":\"54f76bb7404f9990010041b2\"}"
and cat is a JsonObject that I get from my records;
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 .
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.
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 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 :
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:....}"
:
String s = yourId.split["::][1];
String id = s.subString(0, s.length - 1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.