Getting a string value from a JSON array object in Java

EDIT: I really found the answer. I cannot close the question as I am a beginner. I was able to use Array.getString (i) to return the required string value. Thanks for the help.

I have JSON like this:

{ "List": [ "example1", "example2", "example3", "example4" ] } 

And I'm trying to get the string value of these objects without using a key. How can i do this? getString() for jsonObject requires a key, and I don't have one.

+4
source share
3 answers

I assume you have a file: /home/user/file_001.json

the file contains the following: `

 {"age":34,"name":"myName","messages":["msg 1","msg 2","msg 3"]} 

Now write a program that reads the file: /home/user/file_001.json and converts its contents to java JSONObject .

 package org.xml.json; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class JsonSimpleRead { @SuppressWarnings("unchecked") public static void main(String[] args) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader("/home/user/file_001.json")); JSONObject jsonObject = (JSONObject) obj; String name = (String) jsonObject.get("name"); System.out.println(name); long age = (Long) jsonObject.get("age"); System.out.println(age); JSONArray msg = (JSONArray) jsonObject.get("messages"); Iterator<String> iterator = msg.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } } 
+7
source

A list is your key because it is a property of the outermost JSON object:

 JSONObject json = new JSONObject( jsonString ); JSONArray array = json.getArray( "List" ); 
0
source

Another solution:

 import org.json.JSONArray; import org.json.JSONObject; // example json String list = "{\"List\": [\"example1\", \"example2\", \"example3\", \"example4\"]}"; // to parse the keys & values of our list, we must turn our list into // a json object. JSONObject jsonObj = new JSONObject(list); // isolate our list values by our key name (List) String listValues = jsonObj.getString("List"); // turn our string of list values into a json array (to be parsed) JSONArray listItems = new JSONArray(listValues); // now we can print individual values using the getString and // the index of the desired value (zero indexed) Log.d("TAG", listItems.getString(2)); 
0
source

Source: https://habr.com/ru/post/1386446/


All Articles