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..
Related
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.
I am trying to use Jackson in Java to parse a string of Json Array in the format of
"[{"key1":"value1"},{"key2":{"keyChild1":"valueChild1","keyChild2","valueChild2"}}]"
However, the JSON object inside the string of array could be any arbitrary valid JSON, which means I cannot map them to any predefined POJO as suggested in Parsing JSON in Java without knowing JSON format
The goal is to convert this string of JSON array to a List<someObject> that can represent each of the JSON inside the array, and this someObject will allow me to add/remove any key/value pairs in that JSON.
I have tried to use
final ObjectMapper objectMapper = new ObjectMapper();
List<JsonNode> jsonNodes = objectMapper.readValue(jsonArraytring, new TypeReference<List<JsonNode>>() {});
and it seems like the List to be empty. I really got stuck here.
Any help would be appreciated.
try
String json = "[{\"key1\":\"value1\"},{\"key2\":{\"keyChild1\":\"valueChild1\",\"keyChild2\":\"valueChild2\"}}]";
ArrayNode array = (ArrayNode) new ObjectMapper().readTree(json);
You can deserialize the JSON array into a list of maps:
ObjectMapper mapper = new ObjectMapper();
String json = "[{\"key1\":\"value1\"},{\"key2\":{\"keyChild1\":\"valueChild1\",\"keyChild2\":\"valueChild2\"}}]";
List<Object> list = mapper.readValue(json, List.class);
list.forEach(o -> {
System.out.println(o);
System.out.println(o.getClass());
});
Which outpurs:
{key1=value1}
class java.util.LinkedHashMap
{key2={keyChild1=valueChild1, keyChild2=valueChild2}}
class java.util.LinkedHashMap
You can push that even further by calling mapper.readValue(json, Object.class). But then you'll need to know how to use the deserialized types.
You can try the following:
JsonNode node = objectMapper.valueToTree(jsonArraytring);
for(JsonNode innerNode : node.elements()){
//here you have each inner object
}
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.
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.
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.