Using Gson convert Java object into JsonObject - java

I have a Java object, and I want to output it as a JSON string. BUT I want to avoid printing out a property in the Java object. I know that I could do this using GsonBuilder's excludeFieldsWithoutExposeAnnotation() method. However, I thought I'd try the alternate approach of removing the property from the JsonObject before printing it out. The following code works:
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd' 'HH:mm:ss").create();
String javaObjectString = gson.toJson(javaObject);
//javaObjectString currently include "property":"value"
JsonElement jsonElement = gson.toJsonTree(javaObjectString, javaObject.getClass());
JsonObject jsonObject = (JsonObject) jsonElement;
jsonObject.remove("property");
javaObjectString = gson.toJson(jsonObject);
//javaObjectString currently no longer includes "property":"value"
However, it feels a but hacky because I have to output the Java object to a String, and then create a JsonElement from the String, and then cast the JsonElement to a JsonObject.
Is there a more direct way to go from a Java object to a JsonObject?

You don't need the intermediary String. Serialize your Java object to a JsonElement directly with Gson#toJsonTree(Object). Cast that value to whatever type you expect (JSON object, array, or primitive), perform your removal and invoke its toString() method to retrieve its JSON representation as a String.
For example,
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd' 'HH:mm:ss").create();
// JSON data structure
JsonElement jsonElement = gson.toJsonTree(javaObject);
JsonObject jsonObject = (JsonObject) jsonElement;
// property removal
jsonObject.remove("property");
// serialization to String
String javaObjectString = jsonObject.toString();
You can always use the Gson#toJson overload that accepts a JsonElement to serialize it directly to a stream if you want to skip that last String object creation.

Related

How to put data to parsed JSONObject

i have some parse code and to parsed JSONObject i need to add one more JSONObject, but getting error Unexpected token LEFT BRACE({), because my code creating multiply JSONObjects in file, not at parsed JSONObjec. Here is a code, that creating object
aJson = (JSONObject) parser.parse(reader);
JSONObject json = new JSONObject();
JSONArray blockData = new JSONArray();
for(Block b : blocks){
json.put("player-name", p.getName());
json.put("uuid", p.getUniqueId().toString());
json.put("nearestPlayers", new JSONArray());
blockData.add(b.getLocation().getWorld().getName());
blockData.add(b.getLocation().getWorld().getEnvironment());
blockData.add(b.getLocation().getX());
blockData.add(b.getLocation().getY());
blockData.add(b.getLocation().getZ());
}
aJson.put(blockData, json);
Here is JSON
{"[\"world\",NORMAL,-23.0,67.0,75.0]":{"player-name":"MisterFunny01","nearestPlayers":[],"uuid":"206d32da-bf72-3cfd-9a26-e374dd76da31"}} //here is that part// {"[\"world\",NORMAL,-23.0,67.0,75.0]":{"player-name":"MisterFunny01","nearestPlayers":[],"uuid":"206d32da-bf72-3cfd-9a26-e374dd76da31"},"[\"world\",NORMAL,-23.0,67.0,75.0]":{"player-name":"MisterFunny01","nearestPlayers":[],"uuid":"206d32da-bf72-3cfd-9a26-e374dd76da31"}}
In JSON array values must be of type string, number, object, array, boolean or null. Arrays hold values of the same type and not different types.
Looking at your code the array is an array of objects. So you would have to create an object and add the values before adding to the array.
Don't directly add values to the array but create an object and then add to the array.
Your code is wrong. To put an object into JSONObject please read this document
In your case, you need to convert blockData to String to put in the JSONObject.
It's like this: aJson.put(blockData as String, json);
Hope it can be helpful to you.

Access the 2. dimension of a json array (Java)

I have this code:
String sURL = "https://example.com/json"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// 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.
String names = rootobj.get("names").getAsString();
System.out.println(names);
How can I access the second level of the array in the second to last line? "names" ist the first dimension whichs works fine.
In PHP the solution would be
$var = json[...][...] //for accessing the second dimension.
How is this done in Java? Something like rootobj.get("names/surname") doesn't work.
In your Github link, your root element is an array, not an object. (And there's no names attribute)
So you need
root.getAsJsonArray();
Then you would loop over the length of this array, and use a get(i), to access a particular object.
From that object, use another get method to access one attribute of it
According to your code, I assume you use GSON for JSON processing. If your JSON element is an array, you can simply access its elements using get(index). Sketched here:
//Not taking care of possible null values here
JsonObject rootobj = ...
JsonElement elem = rootobj.get("names");
if (elem.isJsonArray()) {
JsonArray elemArray = elem.getAsJsonArray();
JsonElement innerElem = elemArray.get(0);
if (innerElem.isJsonArray()) {
JsonArray innerArray = innerElem.getAsJsonArray();
//Now you can access the elements using get(..)
//E.g. innerArray.get(2);
}
}
Of course this is not that nice to read. You could also take a look at JsonPath, which simplifies navigating to specific parts in your JSON documents.
Update:
In the document you referred to, you want to extract which value exactly? The id value of the array elements (according to one of your comments)? This could be done like this for this example here:
JsonElement root = jp.parse....
JsonArray rootArray = root.getAsJsonArray(); //Without check whether it is really an array
//By the following you would extract the id 6104546
//Access an other array position if you want the second etc. element
System.out.println(rootArray.get(0).getAsJsonObject().get("id"));
Otherwise please explain in more detail what exactly you want (the code you posted does not match with the json examples you refer to).

Java: JSON object containing arrays

I have a Java function that loads JSON from a URL and then returns it as a JSONObject
The function I am using is:
json = new JSONObject(jsonString);
from org.json.JSONObject
The problem is that any arrays being contained in the object are just returned as strings, not as arrays.
We also don't know the format of the JSON being included so we can't specifically call a property of the object to parse. It just has to be able to handle any arrays that might exist.
How can I fix this?
You can use Gson for parsing json string. Its clean and easy.
For using Gson, you need to create a class first describing a single response object like this.
public class ResponseObject {
public String id;
public String name;
}
Now as you already have the json string containing an array of objects, parse the json string as follows.
Gson gson = new Gson();
ResponseObject[] objectArray = gson.fromJson(jsonString, ResponseObject[].class);
Simple!
If you still want the JSONObject, the way you retrieve the array is actually..
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray hobbies = jsonObject.getJSONArray("hobbies");
So that
hobbies.getString(0)
hobbies.getString(1)
etc..
JSONArray itself has .get(), getDouble(), getInt(), etc..

passing JSON array from JavaScript to java and convert JSON array to java array

In my application, I need to pass JSON array to java then convert that array to java array using java as a language. Here is the code.
JavaScript
function arraytofile(rans)
{
myData.push(rans); // rans is the random number
var arr = JSON.stringify(myData);// converting to json array
android.arraytofile(arr); // passing to java
}
Java
public void arraytofile(String newData) throws JSONException {
Log.d(TAG, "MainActivity.setData()");
System.out.println(newData);
}
newData is printing data as [[2],[3],[4]]... I want in regular java array. How I can achieve this?
You can use Google gson . An excellent Java library to work with JSON.
Find it here: https://code.google.com/p/google-gson/
Using gson library classes you can do something like this:
// I took a small sample of your sample json
String json = "[[2],[3],[4]]";
JsonElement je = new JsonParser().parse(json);
JsonArray jsonArray = je.getAsJsonArray();
// I'm assuming your values are in String, you can change this if not
List<String> javaArray = new ArrayList<String>();
for(JsonElement jsonElement : jsonArray) {
JsonArray individualArray = jsonElement.getAsJsonArray();
JsonElement value = individualArray.get(0);
// Again, I'm assuming your values are in String
javaArray.add(value.getAsString());
}
Now you have your json as Java List<String>. That's basically as array.
If you know exact number of results, you can surely define an array of fix size and then assign values to it.
If you know Java, than you already know how to go from here.
I hope this helps.

Is there a way to convert a complex JSON to an object without creating a POJO?

I want to convert a JSON-String to an object. Normally I create an POJO and convert the String to a GSON or JSONObject to my POJO. But is there a better where I don't have to create an POJO?
The goal is to get an object where I can access the keys and values of the JSON... in whatever way, like jsonObject.getKey("foo").getProperty("bar").. or whatever :D
Most JSON parser/generator libraries have a type for each of the JSON types.
Gson has JsonElement and its sub types. Here's an example where you can chain calls.
public static void main(String[] args) throws Exception {
String jsonString = "{\"property1\":\"someValue\", \"arrayProperty\":[{\"first\":1234, \"second\":-13.123}, {\"nested\":\"so deep\"}], \"finally\":\"last\"}";
Gson gson = new Gson();
JsonElement element = gson.fromJson(jsonString, JsonElement.class);
System.out.println(element);
JsonObject jsonObject = element.getAsJsonObject(); // should test type before you do this
System.out.println(jsonObject.get("arrayProperty").getAsJsonArray().get(0));
}
prints
{"property1":"someValue","arrayProperty":[{"first":1234,"second":-13.123},{"nested":"so deep"}],"finally":"last"}
{"first":1234,"second":-13.123}
The above is more or less implemented with a LinkedTreeMap for JsonObject and a List for JsonArray. It provides wrappers to access the elements as more JsonObject, JsonArray, JsonNull, and/or JsonPrimitive instances.

Categories

Resources