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);
Related
I have String "[{...}]" and I want convert it to JSONArray, and then to List list = new List I was trying this solution, and this is my code
public void RestoreData()
{
String toConvert = "[{...}]" // I don't place full String, but it's typical JSONArray, but in String
ArrayList<myClass> listdata = new ArrayList<myClass>();
JsonObject jsonObject = new JsonObject();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.getString(i));
}
}
}
And when I'm trying to compile this I get 2 errors:
In JSONArray jArray = (JSONArray)jsonObject; I get error 'Incovertible types; cannot cast 'org.json.JSONObject' to 'org.json.JSONArray'.
And second: in listdata.add(jArray.getString(i)); I get error 'unhandled exception org.json.JSONException'.
I'm new in Java and I work with Json for the first time.
EDIT
A small truncated example of the Json string:
[{"lootArmorGain":0,"lootBlockGain":0,"lootCost":93500,"lootCritGain":2,"lootCritPowerGain":0,"lootDamageAbsorptionGain":0,"lootDamageGain":0,
}]
I think what you want is:
public void RestoreData()
{
try{
String toConvert = "[{...}]" // I don't place full String, but it's typical JSONArray, but in String
ArrayList<MyClass> listdata = new ArrayList<MyClass>();
JSONArray jsonArray = new JSONArray(toConvert);
if (jsonArray != null) {
Gson gson = new Gson();
for (int i=0;i<jsonArray.length();i++){
String json = jsonArray.getJSONObject(i).toString();
MyClass obj = gson.fromJson(json, MyClass.class);
listdata.add(obj);
}
}
}catch(JSONException e){
e.printStackTrace();
}
}
To convert from JSONOject to your custom class use GSON, see above.
compile 'com.google.code.gson:gson:2.8.4'
Note that your custom class need to have an empty constructor as well as getters and setters in order to make gson work.
I think best approach will be using Google Gson Library.
String toConvert = "[{...}]"
Type listType = new TypeToken<List<myClass>>() {}.getType();
List<myClass> yourList = new Gson().fromJson(toConvert, listType);
You dont need to get each position manually.
For simplicity you can also use Jackson api
ObjectMapper objectMapper = new ObjectMapper();
TypeFactory typeFactory = objectMapper.getTypeFactory();
List<SomeClass> someClassList = objectMapper.readValue(jsonString,typeFactory.constructCollectionType(List.class, SomeClass.class));
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());
}
In my application I get output in the form of Json array as below
{Students: [{Name: Harry,Subject: maths,},
{Name:Ryan,Subject: Biology,},
{Name:James ,Subject: maths,}]}
From this array I want to remove the whole object based on the applied condition.
Lets say if Subject is "Biology" remove the whole object and return:
{Students: [{Name: Harry,Subject: maths,},
{Name:James ,Subject: maths,}]}
How can I achieve this using java programming.
If You have the class (I assume Student here) you can unmarshall the object list using a serialization/deserialization library like Jackson to a collection like List and then do simple list manipulation. Assuming you are receiving the JSON as a string named students
List<Student> list = mapper.readValue(students,
TypeFactory.defaultInstance().constructCollectionType(List.class, Student.class));
This should work.
Edit:
Since you asked for a version that reads JSON from a file, there you go:
public JSONArray getFilteredStudents(String jsonFilePath) throws Exception {
FileReader fileReader = new FileReader(jsonFilePath);
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(fileReader);
JSONArray students = (JSONArray) json.get("Students");
Iterator itr = students.iterator();
while (itr.hasNext()) {
JSONObject obj = (JSONObject) itr.next();
if (obj.get("Subject").equals("Biology")) {
itr.remove();
}
}
return students;
}
Download json-simple library from here.
I want to convert my ArrayList<object> to a JSON String and back to ArrayList<object>
But I really don't know how to do that :
Something like :
Convert
ArrayList<data> arrayData = new ArrayList<data>();
JSONObject retObject = new JSONObject();
retObject.put("data", new JSONArray(arrayData ));
Return convert
idk...
You can consider using a JSON library like Google's Gson library to store and retrieve objects as JSON strings. This is a lightweight library, well regarded and popular. It would be an ideal solution in your case with minimal work required. e.g.,
// How to store JSON string
Gson gson = new Gson();
// This can be any object. Does not have to be an arraylist.
String json = gson.toJson(myAppsArr);
// How to retrieve your Java object back from the string
Gson gson = new Gson();
DataObject obj = gson.fromJson(arrayString, ArrayList.class);
Using Jackson:
ObjectMapper mapper = new ObjectMapper();
String listAsJson = mapper.writeValueAsString(oldList);
List<Object> newList= mapper.readValue(listAsJson ,new TypeReference<List<Object>>() {});
ArrayList<Product> arrayData = new ArrayList<Product>();
Gson gson = new Gson();
convert list to json object
String jsonCartList = gson.toJson(cartList);
convert json to your list
List<Product> prodList = gson.fromJson(jsonCartList, Product.class);
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();