In a Java application with an OrientDB database, after I have a Vertex object, I need to extract its properties in a String object. This object must be in Json format.
An example of expected result is:
{"#type":"d","#rid":"#13:1093","#version":1,"#class":"V_Notification","lastUpdateDate":"2016-07-20 16:45:31","lastUpdateUser":"#12:41","creationDate":"2016-07-20 16:45:31","creationUser":"#12:41","type":"user_added_to_share_made_upload","description":"user_added_to_share_made_upload","sphereId":"#16:18","out_E_NotificationUser":["#45:1091"],"deleted":false,"version":0,"isRead":false,"#fieldTypes":"lastUpdateDate=t,lastUpdateUser=x,creationDate=t,creationUser=x,out_E_NotificationUser=g"}
You could use
OrientVertex v=g.getVertex("#9:0");
ODocument d=v.getRecord();
String json=d.toJSON();
Hope it helps
You can try gson library and than use something like:
Gson gson = new Gson();
String jsonInString = gson.toJson(yourOrientObj);
Ref.: mkyong.com
I made an example to try your case:
#class: V_Notification
Property: description
Vertex v = graph.getVertex("#17:0");
Gson gson = new Gson();
String jsonInString = gson.toJson(v.getProperty("description").toString());
System.out.println("STAMPO = " + jsonInString);
This is my output:
PRINTED = "user_added_to_share_made_upload"
Hope it helps.
Regards.
Related
I'm very sorry if the title is a little misleading... I really don't know what is exactly the terms but don't worry I have provided my code just in case.
I have a JSON string called json_string, this is its value:
{
"record": {
"sample": "Hello World",
"sample_2": "Hello World_2"
},
"metadata": {
"id": "value",
"private": "true"
}
}
I can convert this JSON string to HashMap using this line of code:
myHashMap = new Gson().fromJson(json_string, new TypeToken<HashMap<String, Object>>(){}.getType());
Now I can get the contents of the key record and pass it to string called final_output using this code:
String final_output = myHashMap.get("record").toString();
the string final_output is:
{ sample=Hello World, sample_2=Hello World_2 }
How can I make it return this format again:
{
"sample": "Hello World",
"sample_2": "Hello World_2"
}
?
Thanks for answering
GSON has a built-in method for pretty printing
.setPrettyPrinting()
To enable Gson pretty print, you must configure the Gson instance using the setPrettyPrinting() method of GsonBuilder class and this method configures Gson to output JSON that fits in a page for pretty printing.
For your case:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
myhashmap = gson.fromJson(json_string, new TypeToken<HashMap<String, Object>>(){}.getType());
Update:
You can get the prettified json Object from a key as a String. (here 'record')
String output = gson.toJson(myHashMap.get("record")).toString();
Maybe this example helps you:
SortedMap<String, String> elements = new TreeMap();
elements.put("Key1", "Value1");
elements.put("Key2", "Value2");
elements.put("Key3", "Value3");
Gson gson = new Gson();
Type gsonType = new TypeToken<HashMap>(){}.getType();
String gsonString = gson.toJson(elements,gsonType);
System.out.println(gsonString);
Output:
{"Key1":"Value1","Key2":"Value2","Key3":"Value3"}
For your case:
Gson gson = new Gson();
Type gsonType = new TypeToken<HashMap>(){}.getType();
String final_output = gson.toJson(myHashMap.get("record"),gsonType);
System.out.println(final_output);
This is My String
{Line:1,Direction:incoming,LocalUsername:xxx,AuthUsername:31223,PeerUsername:04232000113,Name:04232000113,Server:23424,Connectime:2189msec,Duration:0msec,DiscBy:Remote,Reason:cancelNormalcallclearing}
i want to convert it to json string
{"Line":"1","Direction":"incoming","LocalUsername":"xxx","AuthUsername":"31223","PeerUsername":"04232000113","Name":"04232000113","Server":"23424","Connectime":"2189msec","Duration":"0msec","DiscBy":"Remote"}
Since it isn't nested, simply add " around : and ,, and after { and before }:
s = s.replaceAll("(?<=[{:,])|(?=[:,}])", "\"");
See demo on regex101.com.
Try using Gson library
Gson g = new Gson();
Player p = g.fromJson(jsonString, Player.class)
You can also convert a Java object to JSON by using toJson() method as shown below
String str = g.toJson(p);
If you don't have a POJO representing the data, it can be done generally using JsonElement.
Demo
String input = "{Line:1,Direction:incoming,LocalUsername:xxx,AuthUsername:31223,PeerUsername:04232000113,Name:04232000113,Server:23424,Connectime:2189msec,Duration:0msec,DiscBy:Remote,Reason:cancelNormalcallclearing}";
Gson g = new Gson();
JsonElement root = g.fromJson(input, JsonElement.class);
String result = g.toJson(root);
System.out.println(result);
Output
{"Line":1,"Direction":"incoming","LocalUsername":"xxx","AuthUsername":31223,"PeerUsername":"04232000113","Name":"04232000113","Server":23424,"Connectime":"2189msec","Duration":"0msec","DiscBy":"Remote","Reason":"cancelNormalcallclearing"}
I am using Java.
I have a string that I have converted to a JSON Object.
I want to extract the value of one of the Keys.
At the moment I am using this code:
String imageId = myJsonObject.getJSONObject("meta")
.getJSONObject("verification")
.getJSONObject("derivedData")
.getJSONArray("images")
.getJSONObject(0)
.getString("imageID");
This code works but surely there must be an easier way. In javascript I could access the value simply by writing this:
myJsonObject.meta.verification.derivedData.images[0].imageId
You may need to install library such as JsonPath to help you select values from a JSON object
An example to help understand better.
You can use external library Gson
Gson gson=new Gson();
/*You can convert to your DTO as well */
Map<Object,Object> map = gson.from(myJsonObject,Map.class);
Other way is using objectmapper example of fasterxml.
ObjectMapper objectMapper=new ObjectMapper();
/*You can convert to your DTO as well */
objectMapper.readValue(data, Map.class);
Try JsonNode by below step
String imageId= jsonNode.
findPath("meta")
.findPath("verification")
.findPath("derivedData")
.findPath("images")
.get (0).findPath ("imageID").asText ();
You need to use the 'Java API for JSON Binding' JSON-B instead of JSON-P. Using JSON-B you can serialize and deserialize between Java objects and data streams and access values of objects POJO style (similar to what you expect).
API details can be found here
A quick start tutorial can be found here and at many website only google search away..
I have created a small class for this purpose which can basically get value from json using a path only used google.gson
https://github.com/izeryab/JsonParser
Here is how to use this for getting nested value from json:
public class Main {
public static void main(String[] args) {
String json = "{\"data\":[{\"stuff\":[\n" + " { \"onetype\":[\n"
+ " {\"id\":1,\"name\":\"John Doe\"},\n" + " {\"id\":2,\"name\":\"Don Joeh\"}\n"
+ " ]},\n" + " {\"othertype\":[\n" + " {\"id\":2,\"company\":\"ACME\"}\n" + " ]}]\n"
+ "},{\"otherstuff\":[\n" + " {\"thing\":\n" + " [[1,42],[2,2]]\n" + " }]\n" + "}]}";
String name = JsonUtil.getJsonElementFromJsonStringUsingPath("data>0>stuff>0>onetype>0>name", json, ">").getAsString();
int id= JsonUtil.getJsonElementFromJsonStringUsingPath("data>0>stuff>0>onetype>0>id",json,">").getAsInt();
System.out.println("id : "+id);
System.out.println("name : "+name);
}
}
Corresponding JAVA DOCS:
https://izeryab.github.io/JsonParser/JsonUtil.html
You can use GSon, I've used it before (see below)
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
JsonArray jsonDataArray = rootobj.getAsJsonArray("data");
JsonPrimitive totalJson = rootobj.getAsJsonPrimitive("total");
JsonPrimitive nextJson = rootobj.getAsJsonPrimitive("next");
Are there any libraries to convert JSON in String/jackson/org.JSON.JSONOBJECT/etc... to a JSON schema?
So far, the only generator I found covert Java classes to JSON schemas. I'm about to write my own converted, but it'd be nice if I didn't have to re-invent the wheel.
looks like there isn't. I had to write my own generator.
Yes there is: https://github.com/java-json-tools/json-schema-validator. It ingests Jacson's JsonNode containing the schema definition and can validate JSON data against that schema.
You can use GSON library.
Convert Java object to JSON:
Gson gson = new Gson();
Staff obj = new Staff();
// 1. Java object to JSON, and save into a file
gson.toJson(obj, new FileWriter("D:\\file.json"));
// 2. Java object to JSON, and assign to a String
String jsonInString = gson.toJson(obj);
Convert JSON to Java object:
Gson gson = new Gson();
// 1. JSON to Java object, read it from a file.
Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);
// 2. JSON to Java object, read it from a Json String.
String jsonInString = "{'name' : 'foo'}";
Staff staff = gson.fromJson(jsonInString, Staff.class);
// JSON to JsonElement, convert to String later.
JsonElement json = gson.fromJson(new FileReader("D:\\file.json"), JsonElement.class);
String result = gson.toJson(json);
I have a String in a following format:
{"id":"1263e246711d665a1fc48f09","facebook_username":"","google_username":"814234576543213456788"}
but sometimes this string looks like:
{"id":"1263e246711d665a1fc48f09","facebook_username":"109774662140688764736","google_username":""}
How can I extract those values if I do not know the index of substrings as they will change for different cases?
That looks like json format, you should give a look to the Gson library by google that will parse that string automatically.
Your class should look like this
public class Data
{
private String id;
private String facebook_username;
private String google_username;
// getters / setters...
}
And then you can simply create a function that create the object from the json string:
Data getDataFromJson(String json){
return (Data) new Gson().fromJson(json, Data.class);
}
That String is formated in JSON (JavaScript Object Notation). Is a common language used to transfer data.
You can parse it using Google's library Gson, just add it to your class path .
Gson gson = new Gson();
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class); //The object you want to convert to.
https://github.com/google/gson
Check this out on how to convert to Java Object
Parsing as JSON notwithstanding, here's a pure string-based solution:
String id = str.replaceAll(".*\"id\":\"(.*?)\".*", "$1");
And similar for the other two, swapping id for the other field names.