java segregate output received from json and pass value to another method - java

I am getting following output on console from the json post request in java using rest api.
{"id":"19494","key":"DF-1079","self":"http://sjira/rest/api/2/issue/19494"}
I need to take just key from this output and pass it on to other method using java.

You can use Gson library for json parsing.
This json library will convert json String to the Object you want. You want keys from it so you can get it parsed to a map and then get key set from it. Pass this key set to other method as per your need.
Code Example
Gson gson = new Gson();
String response= "{\"id\":\"19494\",\"key\":\"DF-1079\",\"self\":\"http://sjira/rest/api/2/issue/19494\"}";
//below line will parse your response to map
Map<String,Object> map = gson.fromJson(response, Map.class);
//get keyset from it pass to some method.
passToSomeMethod(map.keySet())
This keyset will be of type Set. Implementation in method to use it should be accordingly.
Done

You should use entrySet() on json object and populate a List which can be further used as argument in a method or anywhere.
JSONParser parser = new JSONParser();
JSONObject jObj = (JSONObject) parser.parse(postString); // postString contains your response string
List<String> keys = new ArrayList<String>();
for (Entry<String, JsonElement> e : jObj.entrySet()) {
keys.add(e.getKey());
}

Related

JSONObject return empty:false

After some researchs, I didn't have found any solutions to this problem:
when I create a JSONObject (org.json) from a file, it return "empty":false. Why does it return this and how can I fix it?
Java:
JSONObject config = new JSONObject(Files.readAllLines(Paths.get("config/maj.json")));
JSON:
{"FyloZ":"0"}
Files.readAllLines is working return the right value.
Thanks!
Files.readAllLines() returns List<String>, not a String.
So actually you are using the following constructor (accepting a single Object parameter):
https://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.Object-
Construct a JSONObject from an Object using bean getters
The only getter-style method of a List is isEmpty(), so you get that 'empty: false' thing.
Try the following:
String json = new String(Files.readAllBytes(Paths.get("config/maj.json")), "utf-8");
JSONObject config = new JSONObject(json);
Here we read JSON as bytes, convert them to a string (assuming it's in utf-8) and then create a JSONObject from it.

Parsing DBpedia JSON from localhost extraction server in java when the schema isn't known

This is probably a quick answer to a very novice question. I am having trouble wrapping my head around how to get JSON text dbpedia extraction server running from a localhost. The server is running fine, I followed the official instructions.
I have read the other StackOverflow questions about parsing JSON in java and what I am having trouble understanding is how to parse the JSON when the schema or structure is unknown.
For example in my code I try to grab the JSON from localhost and put it into a java object. But all the examples of parsing JSON online use a predesigned java object and all the JSON keys are mapped to an object's fields. (ie Employee class: name,job,email,id,phone)
String sURL = "http://localhost:9999/server/extraction/en/extract?title=" + wikipage + "&revid=&format=rdf-json&extractors=custom"; //just a string
URL url = new URL(sURL);
Reader pageReader = new InputStreamReader(url.openConnection().getInputStream());
Gson g = new Gson();
JsonReader jr = new JsonReader(new InputStreamReader((InputStream) request.getContent()));
jr.setLenient(true);
JsonParser jp = new JsonParser();
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.
I now have this "json object" for the film "Blue Velvet" I can parse/iterate with jr.hasNext() or rootobj.getAsJsonArray().
Am I going about this correctly?
I feel like I am reinventing the wheel. Is there a standard way of parsing DBpedia JSON objects in Java?
At least the Jackson JSON library allows you to parse incoming JSON into a Map. If the keys and values of the JSON can be of any type, then you need to use Map<Object, Object>, which is a bit cumbersome, but anyways this should work:
ObjectMapper mapper = new ObjectMapper();
Map<Object, Object> parsedJSON = mapper.readValue(incomingJSON,
mapper.getTypeFactory().constructMapType(
LinkedHashMap.class,
Object.class,
Object.class));

How to have each record of JSON on a separate line?

When I use JSONArray and JSONObject to generate a JSON, whole JSON will be generated in one line. How can I have each record on a separate line?
It generates like this:
[{"key1":"value1","key2":"value2"}]
I need it to be like following:
[{
"key1":"value1",
"key2":"value2"
}]
You can use Pretty Print JSON Output (Jackson).
Bellow are some examples
Convert Object and print its output in JSON format.
User user = new User();
//...set user data
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));
Pretty Print JSON String
String test = "{\"age\":29,\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"],\"name\":\"myname\"}";
Object json = mapper.readValue(test, Object.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
Reference : http://www.mkyong.com/java/how-to-enable-pretty-print-json-output-jackson/
You may use of the google-gson library for beautifying your JSON string.
You can download the library from here
Sample code :
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJSONString);
String prettyJsonString = gson.toJson(je);
OR
you can use org.json
Sample code :
JSONTokener tokener = new JSONTokener(uglyJsonString); //tokenize the ugly JSON string
JSONObject finalResult = new JSONObject(tokener); // convert it to JSON object
System.out.println(finalResult.toString(4)); // To string method prints it with specified indentation.
Refer answer from this post :
Pretty-Print JSON in Java
The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:
JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4); // stringify with 4 spaces at each level
and please refer this : https://stackoverflow.com/a/2614874/3164682
you can also beautify your string online here.. http://codebeautify.org/jsonviewer
For gettting a easy to read json file you can configure the ObjectMapper to Indent using the following:
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

Convert from LinkedHashMap to Json String

I'm Workin with Mongo using Jongo, when I do a query I receive a LinkedHashMap as result.
Iterator one = (Iterator) friends.find(query).projection("{_id:0}").as(Object.class);
while (one.hasNext()) {
LinkedHashMap data = new LinkedHashMap();
data = (LinkedHashMap) one.next();
String content = data.toString();
}
the problem is that if the json is {"user":"something"} content will be {user=something}, it is not a json is only toString method from HashMap.
How I can get the original JSON?
I don't have a class to map the response and it isn't a solution create a map class, that is why I use a Object.class.
If you have access to some JSON library, it seems like that's the way to go.
If using org.json library, use public JSONObject(java.util.Map map):
String jsonString = new JSONObject(data).toString()
If Gson, use the gson.toJson() method mentioned by #hellboy:
String jsonString = new Gson().toJson(data, Map.class);
You can use Gson library from Google to convert any object to JSON. Here is an example to convert LinkedHashMap to json -
Gson gson = new Gson();
String json = gson.toJson(map,LinkedHashMap.class);
One of the com.mongodb.BasicDBObject constructors takes a Map as input. Then you just have to call the toString() on the BasicDBObject object.
Iterator one = (Iterator) friends.find(query).projection("{_id:0}").as(Object.class);
while (one.hasNext()) {
LinkedHashMap data= new LinkedHashMap();
data= (LinkedHashMap) one.next();
com.mongodb.BasicDBObject bdo = new com.mongodb.BasicDBObject(data);
String json = bdo.toString();
}
I resolved the problem using the following code:
Iterator one = (Iterator) friends.find(query).projection("{_id:0}").as(Object.class);
while (one.hasNext()) {
Map data= new HashMap();
data= (HashMap) one.next();
JSONObject d = new JSONObject();
d.putAll(data);
String content=d.toString();
}
if(data instanceof LinkedHashMap){
json=new Gson.toJson(data,Map.class).toString();
}
else{
json=data.toString();
}
return Document.parse(json);

How to extract json from a json string using GSON?

Below is my JSON String. I am trying to extract hosts from it.
{"description":"DescA","process_running":"sf","hosts":{"dc1":["machineA","machineB"]}}
Since hosts is a JSON String in itself and I would like to extract that JSON String from it. I am using GSON here -
String ss = new String(bytes, Charset.forName("UTF-8"));
// here ss is the above JSON String
Map<String, Object> data = gson.fromJson(ss, Map.class); // parse
I was trying to use Map to deserialize but the result it coming like this in the data-
{description=DescA, process_running=sf, hosts={dc1=[machineA, machineB]}}
Is there any way, I can extract hosts in the JSON format?
The easiest way I can think of to do this would be to use gson to create a tree of json elements from your map, and ask it to give you just the hosts node:
Map<String, Object> data = gson.fromJson(ss, Map.class); // parse
JsonObject jsonTree = (JsonObject) gson.toJsonTree(data);
String hostsJson = jsonTree.get("hosts").toString();

Categories

Resources