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

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;
}

Related

JSON flattener returning only last object from JSON to a flattened form

I have a JSON that looks like below,
{
"users": [
{
"displayName": "Sharad Dutta",
"givenName": "",
"surname": "",
"extension_user_type": "user",
"identities": [
{
"signInType": "emailAddress",
"issuerAssignedId": "kkr007#gmail.com"
}
],
"extension_timezone": "VET",
"extension_locale": "en-GB",
"extension_tenant": "EG12345"
},
{
"displayName": "Sharad Dutta",
"givenName": "",
"surname": "",
"extension_user_type": "user",
"identities": [
{
"signInType": "emailAddress",
"issuerAssignedId": "kkr007#gmail.com"
}
],
"extension_timezone": "VET",
"extension_locale": "en-GB",
"extension_tenant": "EG12345"
}
]
}
I have the above code and it is able to flatten the JSON like this,
{
"extension_timezone": "VET",
"extension_tenant": "EG12345",
"extension_locale": "en-GB",
"signInType": "userName",
"displayName": "Wayne Rooney",
"surname": "Rooney",
"givenName": "Wayne",
"issuerAssignedId": "pdhongade007",
"extension_user_type": "user"
}
But the code is returning only the last user in the "users" array of JSON. It is not returning the first user (essentially the last user only, no matter how many users are there) just the last one is coming out in flattened form from the "users" array.
public class TestConvertor {
static String userJsonAsString;
public static void main(String[] args) throws JSONException {
String userJsonFile = "C:\\Users\\Administrator\\Desktop\\jsonRes\\json_format_user_data_input_file.json";
try {
userJsonAsString = readFileAsAString(userJsonFile);
} catch (Exception e1) {
e1.printStackTrace();
}
JSONObject object = new JSONObject(userJsonAsString); // this is your input
Map<String, Object> flatKeyValue = new HashMap<String, Object>();
System.out.println("flatKeyValue : " + flatKeyValue);
readValues(object, flatKeyValue);
System.out.println(new JSONObject(flatKeyValue)); // this is flat
}
static void readValues(JSONObject object, Map<String, Object> json) throws JSONException {
for (Iterator it = object.keys(); it.hasNext(); ) {
String key = (String) it.next();
Object next = object.get(key);
readValue(json, key, next);
}
}
static void readValue(Map<String, Object> json, String key, Object next) throws JSONException {
if (next instanceof JSONArray) {
JSONArray array = (JSONArray) next;
for (int i = 0; i < array.length(); ++i) {
readValue(json, key, array.opt(i));
}
} else if (next instanceof JSONObject) {
readValues((JSONObject) next, json);
} else {
json.put(key, next);
}
}
private static String readFileAsAString(String inputJsonFile) throws Exception {
return new String(Files.readAllBytes(Paths.get(inputJsonFile)));
}
}
Please suggest where I am doing wrong or my code needs modification.
Please try the below approach, this will give you a comma separated format for both user and identifier (flat file per se),
public static void main(String[] args) throws JSONException, ParseException {
String userJsonFile = "path to your JSON";
final StringBuilder sBuild = new StringBuilder();
final StringBuilder sBuild2 = new StringBuilder();
try {
String userJsonAsString = convert your JSON to string and store in var;
} catch (Exception e1) {
e1.printStackTrace();
}
JSONParser jsonParser = new JSONParser();
JSONObject output = (JSONObject) jsonParser.parse(userJsonAsString);
try {
JSONArray docs = (JSONArray) output.get("users");
Iterator<Object> iterator = docs.iterator();
while (iterator.hasNext()) {
JSONObject userEleObj = (JSONObject)iterator.next();
JSONArray nestedIdArray = (JSONArray) userEleObj.get("identities");
Iterator<Object> nestIter = nestedIdArray.iterator();
while (nestIter.hasNext()) {
JSONObject identityEleObj = (JSONObject)nestIter.next();
identityEleObj.keySet().stream().forEach(key -> sBuild2.append(identityEleObj.get(key) + ","));
userEleObj.keySet().stream().forEach(key -> {
if (StringUtils.equals((CharSequence) key, "identities")) {
sBuild.append(sBuild2.toString());
sBuild2.replace(0, sBuild2.length(), "");
} else {
sBuild.append(userEleObj.get(key) + ",");
}
});
}
sBuild.replace(sBuild.lastIndexOf(","), sBuild.length(), "\n");
}
System.out.println(sBuild);
} catch (Exception e) {
e.printStackTrace();
}
}

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;
}

Java - Get multiple JSON values and turn into String

How would I get all the "name" values and turn them into a String?
So for example if I'd do the following:
System.out.println(value[1]);
It would print out name1.
Here is what I have so far:
JSON:
[
{
"name":"name1"
},
{
"name":"name2",
"changedToAt":1470659096000
},
{
"name":"name3",
"changedToAt":1473435817000
}
]
Java code:
try {
String UUID = p.getUniqueId().toString();
String slimUUID = UUID.replace("-", "");
InputStream in = new URL("https://api.mojang.com/user/profiles/" + slimUUID + "/names").openStream();
String json = IOUtils.toString(in);
IOUtils.closeQuietly(in);
try {
JSONParser parser = new JSONParser();
JSONObject jsonparse = (JSONObject) parser.parse(json);
//get "name" values and turn into String
} catch (ParseException e) {
System.out.println(e.getMessage());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
You need to iterate over array and accumulate all name values into array of Strings.
So below is working source code:
JsonArray jsonObject = new JsonParser()
.parse(json)
.getAsJsonArray();
List<String> names = new ArrayList<>();
for (JsonElement jsonElement : jsonObject) {
names.add(jsonElement.getAsJsonObject().get("name").getAsString());
}
//now you can use as you wish, by index
System.out.println(names.get(1));//returns "name2"
Using the URL from your comment and Java 8 Stream API I've built this main method:
public static void main(final String[] args) throws ParseException, MalformedURLException, IOException {
final String url = "https://api.mojang.com/user/profiles/c8570e47605948d3a3cbe3ec3a681cc0/names";
final InputStream in = new URL(url).openStream();
final String json = IOUtils.toString(in);
IOUtils.closeQuietly(in);
final JSONParser parser = new JSONParser();
final JSONArray jsonparse = (JSONArray) parser.parse(json);
System.out.println(jsonparse);
System.out.println();
final List<String> names = (ArrayList<String>) jsonparse.stream().map((obj) -> {
final JSONObject object = (JSONObject) obj;
return (String) object.getOrDefault("name", "");
}).peek(System.out::println).collect(Collectors.toList());
}
Try My library: abacus-common. All the above can be replaced with:
List<Map<String, Object>> resp = HttpClient.of("https://api.mojang.com/user/profiles/" + slimUUID + "/names").get(List.class);
List<String> names = resp.stream().map(m -> (String) (m.get("name"))).collect(Collectors.toList());
By the way, if slimUUID is equal to: UUID.randomUUID().toString().replaceAll("-", ""). It's be simplified:
List<Map<String, Object>> resp = HttpClient.of("https://api.mojang.com/user/profiles/" + N.guid()+ "/names").get(List.class);
List<String> names = resp.stream().map(m -> (String) (m.get("name"))).collect(Collectors.toList());

Extract JSON Keynames in 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

I can't loop through JSON Array for next Array

I try to learn Loop through a JSON object in Java for loop this case.But My json loop first array(ident AFL274) and stop not loop next array(CQH8971)(in json data have 2 arrays)I call this function by button.
this for call for json
public String getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
for(int i=0;i<data.length();i++)
{
JSONObject data1 = data.getJSONObject(i);
String ans = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return ans;
}
and this JSON:
{
"SearchResult": {
"next_offset": -1,
"aircraft": [
{
"ident": "AFL274",
"type": "B77W"
},
{
"ident": "CQH8971",
"type": "A320"
}
]
}
}
Try this,
public String[] getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
int arrayLength = data.length();
String[] strAryAns = new String[arrayLength];
for(int i=0;i<arrayLength;i++)
{
JSONObject data1 = data.getJSONObject(i);
strAryAns[i] = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return strAryAns;
}

Categories