简体   繁体   中英

getString not working for JSON key

I'm learning how to work with JSON's in java and I'm having a problem using getString for one of my keys. My code is here:

public static void getJSON(String matchID){
    String s = "";
    String test = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"}]}";


    try {
        JSONObject hi = new JSONObject(test);
        JSONArray stuff = hi.getJSONArray("employees");
        String[] items = new String[stuff.length()];
        items[0] = stuff.getString("firstName");
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

The "getString" is underlined in red, and the "The method getString(int) in the type JSONArray is not applicable for the arguments (String)" I was following an answer to another question word for word almost, and this happens, any advice? Thanks! EDIT: I need to get the specifics by name ie. "firstName" because I will be working with thousands of JSONs that each have hundreds of lines.

You need to get the JSOnObject first from the JSONArray(stuff) before you can call getString().

if you want to get the first element in the jsonarray and get its string this is how you would do it

 JsonObject obj = stuff.getJsonObject(0);
 String name = obj.getString("firstname");

So I figured out my problem, I didn't realize I had an JSONObject first, my apologies. Fixed like this:

JSONObject hi = new JSONObject(test);
JSONArray stuff = hi.getJSONArray("employees");         
JSONObject name = stuff.getJSONObject(0);
String[] items = new String[hi.length()];
items[0]=name.getString("firstName");
System.out.println(items[0]);

you can try the simplest way to Parse in JSON

JSONParser parser=new JSONParser();
 String s = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"}]}";
 try{
  Object obj = parser.parse(s);
  JSONArray array = (JSONArray)obj;
  System.out.println(array.get(1));
 }catch(ParseException pe){
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM