I used jackson to convert json strings to json objects / arrays like so:
JSONObject jsonObj = XML.toJSONObject(myXmlString);
JSONObject userObj = jsonObj.getJSONObject("user"); // is there a GSON version of this?
JSONArray orders = userObj.getJSONArray("orders");
My main question is: is there a GSON version of getting json objects / arrays without converting to a pojo? My json is very complex so it's difficult to create pojos.
Secondly, does gson allow you to convert an xml string to json like jackson does (line 1)?
For the first question:
You can create a JsonObject from a json string
String json = "{ \"key1\": \"value1\", \"key2\": false}";
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
otherwise you can create a Map object
String jsonString = "{'employee.name':'Bob','employee.salary':10000}";
Gson gson = new Gson();
Map map = gson.fromJson(jsonString, Map.class);
for reference: https://www.baeldung.com/gson-json-to-map
For the second question:
I found this question in stackoverflow
is there a GSON version of getting json objects / arrays without
converting to a pojo?
Something like this can do the job
import com.google.gson.*;
JsonParser parser = new JsonParser();
JsonElement json = parser.parse(myJsonString);
//get as object
JsonObject obj = json.getAsJsonObject();
//get as array
JsonArray arr = json.getAsJsonArray();
does gson allow you to convert an xml string to json like jackson does
No
Related
In a Domino agent I am reading messages from a messaging service. The message is in JSON format. Is there any approach to parse easily the JSON? The purpose is to create Notes documents from the messages.
The question is too broad what is the json and what have you tried
just a small eg
JsonParser parser = new JsonParser();
String json = "{ \"f1\":\"Hello\",\"f2\":{\"f3:\":\"World\"}}";
JsonElement jsonTree = parser.parse(json);
if(jsonTree.isJsonObject()){
JsonObject jsonObject = jsonTree.getAsJsonObject();
JsonElement f1 = jsonObject.get("f1");
JsonElement f2 = jsonObject.get("f1");
if(f2.isJsonObject()){
JsonObject f2Obj = f2.getAsJsonObject();
JsonElement f3 = f2Obj.get("f3");
}
}
I'm trying to convert Generic ArrayList in JSONArray but it is displaying null value.
but this is working fine if i'm trying to display specific value from ArrayList.
ArrayList<myClass> experience = new ArrayList<>();
... //adding some values
Log.v("testing", experience.get(0).company); //this is showing value
JSONArray json = new JSONArray(experience);
Log.v("testing", json.toString()); //this is showing [null]
There might be a problem recognizing andn converting your "myClass" bean to json.
Try using gson library to create json and to parse it back to object .
Can use GSON library like this:
Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(myCustomList).getAsJsonArray();
Replace with Below Code and try it will work.
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(experience);
Log.e("Jason Array", json);
I'm trying to build a JsonArray of JsonObjects using gson.
Each JsonObject will take the following format,
{"image":"name1"}
{"image":"name2"}
and so on.
I have a string array of the names ("name1","name2",...)
I cannot convert string array directly in to a JsonArray. I'm trying to create JsonObjects iteratively and add it to a JsonArray.
JsonObject innerObject;
JsonArray jArray = new JsonArray();
for(int i = 0; i<names.length; i++)
{
innerObject = new JsonObject();
innerObject.addProperty("image",names[i]);
jArray.add(innerObject);
}
But as I understand, add method in JsonArray takes a JsonElement and here I'm giving a JsonObject. I couldn't find a way to convert JsonObject to JsonElement.
The whole point of using gson will be gone when I do this. Is there a better way?
First, create a class that represents a single json object, e.g.:
class MyObject {
private String image;
public MyObject(String name) { image = name; }
}
Gson will use the class' variable names to determine what property names to use.
Then create an array or list of these using the data you have available, e.g.
ArrayList<MyObject> allItems = new ArrayList<>();
allItems.add(new MyObject("name1"));
allItems.add(new MyObject("name2"));
allItems.add(new MyObject("name3"));
Finally, to serialize to Json, do:
String json = new Gson().toJson(allItems);
And to get the data back from json to an array:
MyObject[] items = new Gson().fromJson(json, MyObject[].class);
For simple (de)serialization, there is no need to be dealing directly with Json classes.
If you are going to use GSON use it like this to convert to object
List<Image>images = new Gson().fromJson(json, Image[].class);
To get json string
String json = new Gson().toJson(images);
That's the point of gson you should not manipulate the data with loops and stuff. You need to take advantage of its powerful model parsing.
Maybe too late but... There is a way to do without creating a new class if you dont need it:
import com.google.gson.JsonObject;
import com.google.gson.JsonArray
...
...
JsonArray jobj = new JsonArray();
String[] names = new String[]{"name1","name2","name3"};
for(String name : names) {
JsonObject item = new JsonObject();
item.addProperty("name",name);
jobj.add(item);
}
System.out.println(jobj.toString());// ;)
Lets say I have following list of custom object: ArrayList<GroupItem> where GroupItem is some class that has int and String variables.
I tried so far Gson library but it's not exactly what I want.
ArrayList<GroupItem> groupsList = /* ... */
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(groupsList, new TypeToken<ArrayList<GroupItem>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
My goal is to get JSONArray (org.Json.JSONArray) somehow. Any ideas?
[EDIT]
My project is Android with Cordova that has API based on org.Json.JSONArray
ANd I thought to write some generic way to convert instances to JSONArray / JSONObject
Thanks,
This way is worked for me:
Convert all list to String.
String element = gson.toJson(
groupsList,
new TypeToken<ArrayList<GroupItem>>() {}.getType());
Create JSONArray from String:
JSONArray list = new JSONArray(element);
The org.json based classes included in Android don't have any features related to converting Java POJOs to/from JSON.
If you have a list of some class (List<GroupItem>) and you absolutely need to convert that to a org.json.JSONArray you have two choices:
A) Use Gson or Jackson to convert to JSON, then parse that JSON into a JSONArray:
List<GroupItem> list = ...
String json = new Gson().toJson(list);
JSONArray array = new JSONArray(json);
B) Write code to create the JSONArray and the JSONObjects it will contain from your Java objects:
JSONArray array = new JSONArray();
for (GroupItem gi : list)
{
JSONObject obj = new JSONObject();
obj.put("fieldName", gi.fieldName);
obj.put("fieldName2", gi.fieldName2);
array.put(obj);
}
Why do you want to use GSON to convert to an org.json class? Nor do you need to write any custom code to get a JSONArray. The org.json api provides a way to do it.
LinkedList list = new LinkedList();
list.add("foo");
list.add(new Integer(100));
list.add(new Double(1000.21));
list.add(new Boolean(true));
list.add(null);
JSONArray jsonArray = new JSONArray(list);
System.out.print(jsonArray);
Use Jackson for JSON to Object or Object to JSON
See the next link Jackson examples
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
StringWriter stringWriter = new StringWriter();
objectMapper.writeValue(stringWriter, groupsList );
System.out.println("groupsList JSON is\n"+stringWrite);
You don't need gson. There's a constructor that takes a collection, so just:
ArrayList<GroupItem> groupsList =... ;
JSONArray JSONArray = new JSONArray(groupsList);
I am using JSONObject to parse nested JSON from an API example:
{"results":[{"congress":"112","state":"NJ","num_results":"2","offset":"0","members": [{"id":"L000123","first_name":"Frank"..........................
I am having trouble accessing the members nested area using JSONObject.
This is my code, any thoughts?
url= new URL("http://api.nytimes.com/svc/politics/v3/us/legislative/congress/112/senate/members.json?&state=NJ&api-key=7967107ef3c9e8d6c2f560027f87904e:17:65990356");
ByteArrayOutputStream urlOutputStream = new ByteArrayOutputStream();
IOUtils.copy(url.openStream(), urlOutputStream);
String urlContents = urlOutputStream.toString();
// parse the JSON object returned
JSONObject jsonO = new JSONObject(urlContents);
System.out.println(jsonO.toString());
JSONObject results = jsonO.getJSONObject("results");
JSONObject senators = results.getJSONObject("members");
You should use third party library like GSON.
http://code.google.com/p/google-gson/