I have this JSON string but I don't know how to reach the "snow" value from the list in "preciptype".
{
"currentConditions": {
"preciptype": ["snow"]
}
}
I have tried the following:
String precipitations;
JSONObject currentConditions = new JSONObject("currentConditions");
precipitations = currentConditions.getString("preciptype");
I know this is not the right solution because "preciptype" is not a string, but I can't wrap my head around how to get "snow" from there. I even tried to loop through it, but it was not working either.
CodePudding user response:
To get the "snow" value from the list in "preciptype", you can use the getJSONArray method to get the list as a JSONArray object, and then use the getString method to get the value at a particular index. Here's an example of how you can do this:
package test.test;
import java.io.FileReader;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
public class App {
public static void main(String[] args) {
String filePath = "D:\\Documents\\workspace\\test\\test\\src\\main\\resources\\test\\test\\test.json";
try (FileReader reader = new FileReader(filePath)) {
JSONTokener tokener = new JSONTokener(reader);
JSONObject json = new JSONObject(tokener);
JSONObject currentConditions = json.getJSONObject("currentConditions");
JSONArray preciptype = currentConditions.getJSONArray("preciptype");
String precipitation = preciptype.getString(0);
System.out.println(precipitation); // prints "snow"
} catch (IOException e) {
} catch (JSONException e) {
e.printStackTrace();
}
}
}