I am trying to figure out (using json-simple) how to get the name of an object within an object. For example:
{ { "objs": { "obj1": "blah", "obj2": "blah" } } }
I would like to get the value obj1
and obj2
(as they're the names of the objects, which is what I want). How would I do this with JSON-Simple and Java and put them into a String[]?
You can use the org.json library.
Maven dependency:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20150729</version>
</dependency>
jar download: http://mvnrepository.com/artifact/org.json/json
Or google gson library
Maven dependency:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.4</version>
</dependency>
jar download: http://mvnrepository.com/artifact/com.google.code.gson/gson/2.4
Org json Example:
import org.json.JSONObject;
.
JSONObject jsonObject = new JSONObject("{ 'objs': { 'obj1': 'blah', 'obj2': 'blah' } } ");
JSONObject objs = jsonObject.getJSONObject("objs");
String obj1 = objs.getString("obj1");
String obj2 = objs.getString("obj1");
System.out.println(obj1);
System.out.println(obj2);
Google gson Example
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
.
JsonParser parser=new JsonParser();
JsonObject object=(JsonObject)parser.parse("{ 'objs': { 'obj1': 'blah', 'obj2': 'blah' } } ");
JsonObject objs2 = object.get("objs").getAsJsonObject();
String value1=objs2.get("obj1").getAsString();
String value2=objs2.get("obj2").getAsString();
System.out.println(value1);
System.out.println(value2);
JSON simple is an old library that is not maintained anymore, last release was on 2012. google gson
and org json
last releases were on 2015, anyway, if you want to use the old library, take a look to the documentation: