Extract JSON Keynames in Java - java

I want to extract JSON structure (only keyNames structure) by preserving the hierarchy (parent child relationship); I don't want values from the JSON yet.
I am new to Java and have been tying to achieve this using Jackson , but with no success.
Any direction on this will be much appreciated.

I created a static inner class for you by using JSONObject (http://www.json.org/javadoc/org/json/JSONObject.html)
public static class KeyNode {
private String name;
private ArrayList<KeyNode> children;
public KeyNode(String name) {
this.name = name;
this.children = new ArrayList<KeyNode>();
}
public void addChild(KeyNode child) {
this.children.add(child);
}
public static void parseJsonToKeys(KeyNode node, JSONObject json) throws JSONException {
Iterator<?> keys = json.keys();
while (keys.hasNext()) {
String name = (String) keys.next();
KeyNode child = new KeyNode(name);
node.addChild(child);
if (json.optJSONObject(name) != null) {
parseJsonToKeys(child, json.getJSONObject(name));
} else if (json.optJSONArray(name) != null) {
JSONArray array = json.getJSONArray(name);
for (int i = 0; i < array.length(); i++) {
try {
array.getJSONObject(i);
parseJsonToKeys(child, json.getJSONObject(name));
} catch (JSONException e) {
// this is ok
}
}
}
}
}
public static void exampleCodeUsage() {
try {
JSONObject json = new JSONObject("your json");
KeyNode keyHierarchy = new KeyNode("root");
parseJsonToKeys(keyHierarchy, json);
} catch (JSONException e) {
// your json is not formatted correctly
}
}
}

JSONParser parser = parser;
Object obj = parser.parse(new FileReader(FileName.Json));
JSONObject jobj = (JSONObject) obj;
obj.keys()
The method will give you the list of all keys in JSONObject

Related

Java: How do I create this JSON Array Structure using GSON

I want to create a JSON array structure like this or append an object to the structure
{ "user" : [
{"name" : "user1", "email": "user1#gmail"},
{"name": "user2", "email": "user2#gmail"}
]
}
I'm using GSON to write this into a file
public void appendToObject(File jsonFile, String key, String value) {
Objects.requireNonNull(jsonFile);
Objects.requireNonNull(key);
Objects.requireNonNull(value);
if (jsonFile.isDirectory()) {
throw new IllegalArgumentException("File can not be a directory!");
}
try {
JsonObject node = readOrCreateNew(jsonFile);
JsonArray userArray = new JsonArray();
userArray.add(user(key,value));
node.add("user", userArray);
FileWriter writer = new FileWriter(jsonFile)
gson.toJson(node, writer);
}catch (Exception e)
{
Log.d("display1", "appendToObject: error"+e.getLocalizedMessage());
e.printStackTrace();
}
}
private JsonObject user(String user, String password){
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", user);
jsonObject.addProperty("password", password);
return jsonObject;
}
private JsonObject readOrCreateNew(File jsonFile) throws IOException {
if (jsonFile.exists() && jsonFile.length() > 0) {
try (BufferedReader reader = new BufferedReader(new FileReader(jsonFile))) {
return gson.fromJson(reader, JsonObject.class);
}
}
return new JsonObject();
}
Here's the code with suggestions integrated and with reading and writing JSON file functions
but im getting "user1":"{\"values\":[null,\"user13\",\"useremail13\"]}"}
how to structure it so that I get the desired output
I omitted some your code in appendToObject. But the meaning should be clear.
public void appendToObject(File jsonFile, String key, String value) {
...
JsonObject node = readOrCreateNew(jsonFile);
JsonObject newUser = user(key, value);
JsonElement user = node.get("user");
if (user != null && user.isJsonArray()){
((JsonArray) user).add(newUser);
} else {
JsonObject root = new JsonObject();
node.add("user", createArray(newUser));
}
...
}
private JsonObject createUserArray(JsonObject ... objects){
JsonArray userArray = new JsonArray();
for (JsonObject user : objects) {
userArray.add(user);
}
return userArray;
}
private JsonObject user(String email, String name){
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", name);
jsonObject.addProperty("email", email);
return jsonObject;
}

How to return a JSONObject instead HashMap with ResponseEntity? (No converter found for return value of type: class org.json.JSONObject)

I am able to return an HashMap as a JSON from my REST API built on Spring Boot. Here my Method:
#ResponseBody
#Transactional
#GetMapping("create_coinmarketcap_snapshot")
public ResponseEntity<HashMap> create_coinmarketcap_snapshot() {
String jsonString = callURL("https://api.coinmarketcap.com/v2/ticker/?limit=5");
JSONArray coinmarketcapsnapshotsArray = new JSONArray();
JSONObject coinmarketcapsnapshotsJSONObject = new JSONObject();
HashMap<Integer, CoinmarketcapSnapshot> coinmarketcapsnapshotsHashMap = new HashMap<>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject jsonObjectData = jsonObject.getJSONObject("data");
Iterator<?> keys = jsonObjectData.keys();
int count = 0;
while (keys.hasNext()) {
count++;
String key = (String) keys.next();
if (jsonObjectData.get(key) instanceof JSONObject) {
JSONObject jsonObjectDataCrypto = jsonObjectData.getJSONObject(key);
JSONObject jsonObjectDataCryptoQuotes = jsonObjectDataCrypto.getJSONObject("quotes").getJSONObject("USD");
CoinmarketcapSnapshot coinmarketcapsnapshotObject = new CoinmarketcapSnapshot();
String dateFormatted = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
coinmarketcapsnapshotObject.setTitle(jsonObjectDataCrypto.get("name") + " - " + dateFormatted);
coinmarketcapsnapshotObject.setCryptocurrencyId((int) jsonObjectDataCrypto.get("id"));
if(jsonObjectDataCrypto.get("rank")!=null){
coinmarketcapsnapshotObject.setRank((int) jsonObjectDataCrypto.get("rank"));
}
if(jsonObjectDataCrypto.get("circulating_supply")!=null){
coinmarketcapsnapshotObject.setCirculatingSupply((Double) jsonObjectDataCrypto.get("circulating_supply"));
}
if(jsonObjectDataCrypto.get("total_supply")!=null){
coinmarketcapsnapshotObject.setTotalSupply((Double) jsonObjectDataCrypto.get("total_supply"));
}
if(!jsonObjectDataCrypto.isNull("circulating_supply")) {
coinmarketcapsnapshotObject.setMaxSupply((Double) jsonObjectDataCrypto.get("circulating_supply"));
}
if(!jsonObjectDataCrypto.isNull("total_supply")) {
coinmarketcapsnapshotObject.setMaxSupply((Double) jsonObjectDataCrypto.get("total_supply"));
}
if(!jsonObjectDataCrypto.isNull("max_supply")) {
coinmarketcapsnapshotObject.setMaxSupply((Double) jsonObjectDataCrypto.get("max_supply"));
}
if(!jsonObjectDataCryptoQuotes.isNull("price")) {
coinmarketcapsnapshotObject.setPrice((Double) jsonObjectDataCryptoQuotes.get("price"));
}
if(!jsonObjectDataCryptoQuotes.isNull("volume_24h")) {
coinmarketcapsnapshotObject.setVolume24h((Double) jsonObjectDataCryptoQuotes.get("volume_24h"));
}
if(!jsonObjectDataCryptoQuotes.isNull("market_cap")) {
coinmarketcapsnapshotObject.setMarketCap((Double) jsonObjectDataCryptoQuotes.get("market_cap"));
}
if(!jsonObjectDataCryptoQuotes.isNull("percent_change_1h")) {
coinmarketcapsnapshotObject.setPercentChange1h((Double) jsonObjectDataCryptoQuotes.get("percent_change_1h"));
}
if(!jsonObjectDataCryptoQuotes.isNull("percent_change_24h")) {
coinmarketcapsnapshotObject.setPercentChange24h((Double) jsonObjectDataCryptoQuotes.get("percent_change_24h"));
}
if(!jsonObjectDataCryptoQuotes.isNull("percent_change_7d")) {
coinmarketcapsnapshotObject.setPercentChange7d((Double) jsonObjectDataCryptoQuotes.get("percent_change_7d"));
}
entityManager.persist(coinmarketcapsnapshotObject);
coinmarketcapsnapshotsArray.put(coinmarketcapsnapshotObject);
coinmarketcapsnapshotsJSONObject.put(String.valueOf(count),coinmarketcapsnapshotObject);
coinmarketcapsnapshotsHashMap.put(count, coinmarketcapsnapshotObject);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("\n\ncoinmarketcapsnapshotsArray:\n"+coinmarketcapsnapshotsArray);
System.out.println("\n\ncoinmarketcapsnapshotsJSONObject:\n"+coinmarketcapsnapshotsJSONObject);
System.out.println("\n\ncoinmarketcapsnapshotsHashMap:\n"+coinmarketcapsnapshotsHashMap);
return new ResponseEntity<>(coinmarketcapsnapshotsHashMap, HttpStatus.OK);
}
Here is what is printed in the terminal:
coinmarketcapsnapshotsArray:
["com.krown.entity.CoinmarketcapSnapshot#4d60f69f","com.krown.entity.CoinmarketcapSnapshot#4739c2f2","com.krown.entity.CoinmarketcapSnapshot#7d5bd573","com.krown.entity.CoinmarketcapSnapshot#43b5eb6d","com.krown.entity.CoinmarketcapSnapshot#26e1a633"]
coinmarketcapsnapshotsJSONObject:
{"1":"com.krown.entity.CoinmarketcapSnapshot#4d60f69f","2":"com.krown.entity.CoinmarketcapSnapshot#4739c2f2","3":"com.krown.entity.CoinmarketcapSnapshot#7d5bd573","4":"com.krown.entity.CoinmarketcapSnapshot#43b5eb6d","5":"com.krown.entity.CoinmarketcapSnapshot#26e1a633"}
coinmarketcapsnapshotsHashMap:
{1=com.krown.entity.CoinmarketcapSnapshot#4d60f69f, 2=com.krown.entity.CoinmarketcapSnapshot#4739c2f2, 3=com.krown.entity.CoinmarketcapSnapshot#7d5bd573, 4=com.krown.entity.CoinmarketcapSnapshot#43b5eb6d, 5=com.krown.entity.CoinmarketcapSnapshot#26e1a633}
I want to return my JSONObject "coinmarketcapsnapshotsJSONObject" instead "coinmarketcapsnapshotsHashMap", but when I do it, I keep getting stuck with this error:
No converter found for return value of type: class org.json.JSONObject
As suggested in some posts found on web, I added Jackson as new dependency in pom.xml file:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
Unfortunately this didn't change anything.
Do you have any suggestion to improve the process of building a JSON for a REST API on Spring Boot?
When I return the HashMap, the output looks like that:
#GetMapping(produces={MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<?> create_coinmarketcap_snapshot() throws IOException {
UriComponentsBuilder builder =
UriComponentsBuilder.fromUriString("https://api.coinmarketcap.com/v2/ticker")
.queryParam("limit", "5");
ResponseEntity<String> response =
restTemplate.getForEntity(builder.toUriString(), String.class);
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(response.getBody());
JsonNode data = root.path("data");
data.forEach(jsonObject -> {
jsonObject.get("rank"); //extracting values from each json object
jsonObject.get("circulating_supply");
jsonObject.get("total_supply");
jsonObject.get("max_supply");
jsonObject.get("price");
jsonObject.get("volume_24h");
jsonObject.get("market_cap");
jsonObject.get("percent_change_1h");
jsonObject.get("percent_change_24h");
//... and so on
});
return ResponseEntity.ok(data);
}
Now you're returning a json object that contains the value of "data" key #118218
HttpStatus.OK is the default return value for Http endpoints using Spring and therefore specifying it is unnecessary, thereby rendering the entire ResponseEntity unnecessary:
#ResponseBody
#Transactional
#GetMapping("create_coinmarketcap_snapshot")
public HashMap create_coinmarketcap_snapshot() {
String jsonString = callURL("https://api.coinmarketcap.com/v2/ticker/?limit=5");
JSONArray coinmarketcapsnapshotsArray = new JSONArray();
JSONObject coinmarketcapsnapshotsJSONObject = new JSONObject();
HashMap<Integer, CoinmarketcapSnapshot> coinmarketcapsnapshotsHashMap = new HashMap<>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject jsonObjectData = jsonObject.getJSONObject("data");
Iterator<?> keys = jsonObjectData.keys();
int count = 0;
while (keys.hasNext()) {
count++;
String key = (String) keys.next();
if (jsonObjectData.get(key) instanceof JSONObject) {
JSONObject jsonObjectDataCrypto = jsonObjectData.getJSONObject(key);
JSONObject jsonObjectDataCryptoQuotes = jsonObjectDataCrypto.getJSONObject("quotes").getJSONObject("USD");
CoinmarketcapSnapshot coinmarketcapsnapshotObject = new CoinmarketcapSnapshot();
String dateFormatted = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
coinmarketcapsnapshotObject.setTitle(jsonObjectDataCrypto.get("name") + " - " + dateFormatted);
coinmarketcapsnapshotObject.setCryptocurrencyId((int) jsonObjectDataCrypto.get("id"));
if(jsonObjectDataCrypto.get("rank")!=null){
coinmarketcapsnapshotObject.setRank((int) jsonObjectDataCrypto.get("rank"));
}
if(jsonObjectDataCrypto.get("circulating_supply")!=null){
coinmarketcapsnapshotObject.setCirculatingSupply((Double) jsonObjectDataCrypto.get("circulating_supply"));
}
if(jsonObjectDataCrypto.get("total_supply")!=null){
coinmarketcapsnapshotObject.setTotalSupply((Double) jsonObjectDataCrypto.get("total_supply"));
}
if(!jsonObjectDataCrypto.isNull("circulating_supply")) {
coinmarketcapsnapshotObject.setMaxSupply((Double) jsonObjectDataCrypto.get("circulating_supply"));
}
if(!jsonObjectDataCrypto.isNull("total_supply")) {
coinmarketcapsnapshotObject.setMaxSupply((Double) jsonObjectDataCrypto.get("total_supply"));
}
if(!jsonObjectDataCrypto.isNull("max_supply")) {
coinmarketcapsnapshotObject.setMaxSupply((Double) jsonObjectDataCrypto.get("max_supply"));
}
if(!jsonObjectDataCryptoQuotes.isNull("price")) {
coinmarketcapsnapshotObject.setPrice((Double) jsonObjectDataCryptoQuotes.get("price"));
}
if(!jsonObjectDataCryptoQuotes.isNull("volume_24h")) {
coinmarketcapsnapshotObject.setVolume24h((Double) jsonObjectDataCryptoQuotes.get("volume_24h"));
}
if(!jsonObjectDataCryptoQuotes.isNull("market_cap")) {
coinmarketcapsnapshotObject.setMarketCap((Double) jsonObjectDataCryptoQuotes.get("market_cap"));
}
if(!jsonObjectDataCryptoQuotes.isNull("percent_change_1h")) {
coinmarketcapsnapshotObject.setPercentChange1h((Double) jsonObjectDataCryptoQuotes.get("percent_change_1h"));
}
if(!jsonObjectDataCryptoQuotes.isNull("percent_change_24h")) {
coinmarketcapsnapshotObject.setPercentChange24h((Double) jsonObjectDataCryptoQuotes.get("percent_change_24h"));
}
if(!jsonObjectDataCryptoQuotes.isNull("percent_change_7d")) {
coinmarketcapsnapshotObject.setPercentChange7d((Double) jsonObjectDataCryptoQuotes.get("percent_change_7d"));
}
entityManager.persist(coinmarketcapsnapshotObject);
coinmarketcapsnapshotsArray.put(coinmarketcapsnapshotObject);
coinmarketcapsnapshotsJSONObject.put(String.valueOf(count),coinmarketcapsnapshotObject);
coinmarketcapsnapshotsHashMap.put(count, coinmarketcapsnapshotObject);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("\n\ncoinmarketcapsnapshotsArray:\n"+coinmarketcapsnapshotsArray);
System.out.println("\n\ncoinmarketcapsnapshotsJSONObject:\n"+coinmarketcapsnapshotsJSONObject);
System.out.println("\n\ncoinmarketcapsnapshotsHashMap:\n"+coinmarketcapsnapshotsHashMap);
return coinmarketcapsnapshotsHashMap;
}

Dealing with different JSONArray types

I have a program that reads in a simple JSON file and manipulates the data. I then store this data in trees (albeit badly). I have a problem where arguments can longs e.g {1,2}, longs and variables e.g {1,x2}, or variables with other variables e.g. {x1,x2}.
I have been able to retrieve the variables from the JSONArray. The problem arises when I have a variable and a value. I can't for the life of me figure out how to deal with such an occurrence. I apologise for the excessive use of try-catch operations. If anyone could help me solve this issue, it would be much appreciated.
public class program {
public static void main(String[] args) throws IOException {
File file = new File();
File outputfile = new File();
PrintWriter pw = new PrintWriter(new BufferedWriter(new
FileWriter(outputfile, true)));
JSONParser parser = new JSONParser();
try {
// creates object of parsed file
Object object = parser.parse(new FileReader(file));
// casts object to jsonObject
JSONObject jsonObject = (JSONObject) object;
// gets declaration-list JSONArray from the object created.
JSONArray jsonArray = (JSONArray) jsonObject.get("declaration-list");
// Surrounding this in a try-catch would allow me to deal with the
// different value cases unlike the frist time i wrote it
try {
/*
* iterator to cycle through the array. Made the mistake last
* time of continuously calling a method
*/
Iterator iterator = jsonArray.iterator();
while (iterator.hasNext()) {
JSONObject jo = (JSONObject) iterator.next();
String variableName = (String) jo.get("declared-variable");
MyTreeNode<String> root = new MyTreeNode<>(variableName);
try {
long value = (long) jo.get("value");
MyTreeNode<Long> child1 = new MyTreeNode(value);
System.out.println(root.getData());
root.addChild(child1);
for (MyTreeNode node : root.getChildren()) {
System.out.println(node.getData());
}
test.put(variableName, value);
// numPrint(test, variableName, pw);
} catch (Exception e) {
final JSONObject jsonValue = (JSONObject) jo.get("value");
final String operator = (String) jsonValue.get("operator");
final JSONArray arguments = (JSONArray) jsonValue.get("arguments");
ArrayList values[] = new ArrayList[arguments.size()];
if (operator.equals("set")) {
for(int i = 0; i < arguments.size(); i++){
try{
//prints nested variables
JSONObject jtest = (JSONObject) arguments.get(i);
String varval = (String) jtest.get("variable");
System.out.println(varval);
}catch(Exception g){
}
}
MyTreeNode<myObject> test1 = new MyTreeNode(new myObject(operator, arguments));
root.addChild(test1);
for (MyTreeNode node : root.getChildren()) {
System.out.print(root.getData());
System.out.print(" = ");
System.out.println(node.getData());
}
}
if (operator.equals("pair")) {
MyTreeNode<myObject> test1 = new MyTreeNode(new myObject(operator, arguments));
root.addChild(test1);
for (MyTreeNode node : root.getChildren()) {
System.out.print(root.getData() + " = ");
System.out.println(node.getData());
}
}
}
}
} catch (Exception e) {
System.out.println("oops");
}
} catch (FileNotFoundException e) {
System.out.println("Input file not found");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
System.out.println("File was not parsed");
e.printStackTrace();
}
pw.flush();
pw.close();
}
}
class MyTreeNode<T> {
private T data = null;
private List<MyTreeNode> children = new ArrayList<>();
private MyTreeNode parent = null;
public MyTreeNode(T data) {
this.data = data;
}
public void addChild(MyTreeNode child) {
child.setParent(this);
this.children.add(child);
}
public void addChild(T data) {
MyTreeNode<T> newChild = new MyTreeNode<>(data);
newChild.setParent(this);
children.add(newChild);
}
public void addChildren(List<MyTreeNode> children) {
for (MyTreeNode t : children) {
t.setParent(this);
}
this.children.addAll(children);
}
public List<MyTreeNode> getChildren() {
return children;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
private void setParent(MyTreeNode parent) {
this.parent = parent;
}
public MyTreeNode getParent() {
return parent;
}
}
class myObject {
String operator;
JSONArray arguments;
public myObject(String operator, JSONArray arguments) {
this.operator = operator;
this.arguments = arguments;
}
public JSONArray get() {
return arguments;
}
public String toString() {
if (arguments.size() == 0) {
return "{}";
}
if (operator.equals("pair")) {
return "(" + arguments.get(0) + "," + arguments.get(1) + ")";
} else if (operator.equals("set")) {
String concat = "{" + arguments.get(0);
for (int i = 1; i < arguments.size(); i++) {
concat += "," + arguments.get(i);
}
return concat += "}";
}
return "wot";
}
}
In order to process the JSONArray, I suggest that you create a method which checks the type of the object first and then delegates the processing to other specialised methods based on its type.
This will allow you re-use the code in case you have arrays in arrays and also to navigate through the JSON tree.
Something along these lines:
private static void processArray(JSONArray jsonArray) {
jsonArray.forEach(o -> {
if (o instanceof Number) {
processNumber((Number) o);
} else if (o instanceof JSONObject) {
process((JSONObject) o);
} else if (o instanceof String) {
process((String) o);
} else if (o instanceof JSONArray) {
processArray((JSONArray) o); // recursive call here.
}
});
}
Other methods would look like:
private static void process(String o) {
System.out.println(o); // just an example
}
public static void processNumber(Number number) {
System.out.println(number); // just an example
}
And the most complex would be the one for processing objects:
private static void process(JSONObject o) {
o.forEach((s, o1) -> {
System.out.println(s);
if (o1 instanceof Number) {
processNumber((Number) o1);
} else if (o1 instanceof JSONObject) {
process((JSONObject) o1); // recursion
} else if (o1 instanceof String) {
process((String) o1);
} else if (o1 instanceof JSONArray) {
processArray((JSONArray) o1);
}
});
}
This method would also be recursive. With this type of approach you can navigate through all objects in the tree.
Update:
If you want to process JSON like:
{
"declared-variable": "x17",
"value": {
"operator": "set",
"arguments": [
1,
2,
{
"variable": "x8"
}
]
}
}
you can do so by creating a main method similar to this one:
public static void main(String[] args) throws IOException, ParseException {
JSONParser jsonParser = new JSONParser(JSONParser.MODE_JSON_SIMPLE);
try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("array_mixed.json")) {
Object obj = jsonParser.parse(in);
if (obj instanceof JSONArray) {
processArray((JSONArray) obj);
}
else if(obj instanceof Object) {
process((JSONObject) obj);
}
}
}
This main method together with the other methods described can at least print out all the elements in the JSON.
You should be able to at least print out the following in the case of the specified JSON above:
declared-variable
x17
value
arguments
1
2
variable
x8
operator
set

Read out from another method

So I got this piece of code:
public static ArrayList<Vehicle> readVehicles() throws IOException {
ArrayList<Vehicle> out = new ArrayList<Vehicle>();
JSONParser parser = new JSONParser();
JSONObject jsonObject = new JSONObject();
try {
jsonObject = (JSONObject) parser.parse(new FileReader("Vehicles.json"));
} catch (ParseException e) {
e.printStackTrace();
}
JSONArray jsonvehicles = (JSONArray) jsonObject.get("Vehicles");
Iterator i = jsonvehicles.iterator();
while (i.hasNext()) {
JSONObject v = (JSONObject) i.next();
/*
* Engines(); Chassis(); Tires();
*/
// out.add(new Vehicle(...);
}
return out;
}
public static ArrayList<Engine> readEngines() throws IOException {
ArrayList<Engine> out = new ArrayList<Engine>();
JSONParser parser = new JSONParser();
JSONObject jsonObject = new JSONObject();
try {
jsonObject = (JSONObject) parser.parse(new FileReader("Engines.json"));
} catch (ParseException e) {
e.printStackTrace();
}
JSONArray jsonengines = (JSONArray) jsonObject.get("Engines");
Iterator i = jsonengines.iterator();
while (i.hasNext()) {
JSONObject v = (JSONObject) i.next();
String name = (String) v.get("name");
int price = (int) v.get("price");
int quality = (int) v.get("quality");
int maxSpeed = (int) v.get("maxSpeed");
int maxAccelaration = (int) v.get("maxAcceleration");
out.add(new Engine(name, price, quality, maxSpeed, maxAccelaration));
}
return out;
}
and so on, regarding at tires(), and chassis.
My question is, how do I get the output of for example, engine, into vehicle?
See, a vehicle consists of engines, chassis and tires. And a engine as the properties quality, name, price and so on. How do I kinda add this to a new vehicle?
It's probably already been asked, but I really don't know how to ask this (native language isn't English). Sorry if I sound really vague, but to be honest, I'm not sure what I'm asking.
As Kevin Esche said, you can do it by something like this (For example) :
Car.java class file
private class Car{
private Engine engine;
private ArrayList<Tire> tires;
public void setEngine(Engine carEngine){
this.engine = carEngine;
}
public Engine getEngine(){
return this.engine;
}
public void addTire(Tire carTire){
this.tires.add(carTire);
}
}
Engin java class file
private class Engine{
private int horsepower;
public int getHorsepower() {
return horsepower;
}
public void setHorsepower(int horsepower) {
this.horsepower = horsepower;
}
}
Tire.java file
private class Tire{
private int size;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
In addition, something is missing in your "readVehicle()" method code.
You need to write how to build a Vehicule from your Json Object.
So if your json file looks like :
{
"carType": "Mercedes Classe B"
}
you will need to write in your code (readVehicle() method for example):
Vehicule vehicule = new Vehicle();
vehicule.setType(object.getString("carType"));

Convert string to JSON and get value

I have this string:
{"markers":[{"tag":"1","dep":"2"}]}
How to convert it to JSON and get value tag and dep?
you need JSONObject to do this
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET,url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String tag, dep;
JSONArray jArray = response.getJSONArray("markers");
JSONObject msg = jArray.getJSONObject(0);
tag = msg.getString("tag");
dep = msg.getString("dep");
}
}
try
{
JSONObject object = new JSONObject(json_str);
JSONArray array= object.getJSONArray("markers");
for(int i=0;i<array.length();i++)
{
JSONObject obj= array.getJSONObject(i);
String tag= obj.getString("tag");
int dep= obj.getInt("dep");
}
}catch(JSONException e){
}
Hope this helps.
it's good habbit to serialize the json to pojo object ..
here you can use Gson (a google library to serialize/deserialize json to pojo object)
Assuming you are using Android-Studio IDE for android development
Step 1 : add this gson dependency on build.gradle file of module scope
compile 'com.google.code.gson:gson:2.4'
Step 2: create model for json
{"markers":[{"tag":"1","dep":"2"}]}
Markers.java
public class Markers {
/**
* tag : 1
* dep : 2
*/
private List<MarkersEntity> markers;
public void setMarkers(List<MarkersEntity> markers) {
this.markers = markers;
}
public List<MarkersEntity> getMarkers() {
return markers;
}
public static class MarkersEntity {
private String tag;
private String dep;
public void setTag(String tag) {
this.tag = tag;
}
public void setDep(String dep) {
this.dep = dep;
}
public String getTag() {
return tag;
}
public String getDep() {
return dep;
}
}
}
Step 3: serialise json string to pojo object using gson
Gson gson = new Gson();
Markers markers = gson.fromJson(<jsonstring>.toString(), Markers.class);
Step 4: iterate the markers.getMarkersEntity() to get values of tag & dep
for(MarkersEntity data:markers.getMarkersEntity())
{
String tag = data.getTag();
String dep = data.getDep();
Log.d("JSON to Object", tag +"-"+dep);
}
You can use Ion Library for this and parse it as follows:
Ion.with(MainActivity.this).load("url").asJsonObject().setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception arg0, JsonObject arg1) {
// TODO Auto-generated method stub
if(arg0==null)
{
arg1.get("markers").getAsJsonArray();
JsonObject Jobj=arg1.getAsJsonObject();
String tag=Jobj.get("tag").getAsString();
String dep=Jobj.get("dep").getAsString();
}
}
});
Here, you may find your solution. Try it.
try {
//jsonString : {"markers": [{"tag":"1","dep":"2"}]}
JSONObject mainObject = new JSONObject(jsonString);
JSONArray uniArray = mainObject.getJSONArray("markers");
JSONObject subObject = uniArray.getJSONObject(0);
String tag = subObject.getString("tag");
String dep = subObject.getString("dep");
} catch (JSONException e) {
e.printStackTrace();
}

Categories