How to parse JSON and get only one field?
First of all include the JSON
Library in your project.
Then iterate through your JSON like this:
JSONArray firstLevelArrray = new JSONArray(jsonString); // Getting the big array
for(int i = 0 ; i < firstLevelArrray.length(); i++)
{
Integer length = firstLevelArray.getJSONObject(i) // getting the first object of the array
.getJSONArray("sections") // Getting the sections array
.getJSONObject(0) // Getting the first element of the sections array
.getJSONObject("summary")
.getInt("length");
// But how sure are you that you won't have a null in there?
}
I still wouldn't go this way, there is a big possibility of a NullPointerException
in there. You can always handle it and treat it as if the field was not in there, but still...
Parsing JSON string in Java
See my comment.
You need to include the full org.json library when running as android.jar only contains stubs to compile against.
In addition, you must remove the two instances of extra }
in your JSON data following longitude
.
private final static String JSON_DATA =
"{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " ]"
+ "}";
Apart from that, geodata
is in fact not a JSONObject
but a JSONArray
.
Here is the fully working and tested corrected code:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ShowActivity {
private final static String JSON_DATA =
"{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " ]"
+ "}";
public static void main(final String[] argv) throws JSONException {
final JSONObject obj = new JSONObject(JSON_DATA);
final JSONArray geodata = obj.getJSONArray("geodata");
final int n = geodata.length();
for (int i = 0; i < n; ++i) {
final JSONObject person = geodata.getJSONObject(i);
System.out.println(person.getInt("id"));
System.out.println(person.getString("name"));
System.out.println(person.getString("gender"));
System.out.println(person.getDouble("latitude"));
System.out.println(person.getDouble("longitude"));
}
}
}
Here's the output:
C:\dev\scrap>java -cp json.jar;. ShowActivity
1
Julie Sherman
female
37.33774833333334
-121.88670166666667
2
Johnny Depp
male
37.336453
-121.884985
Parsing a JSON component whose structure is always changing in JAVA
Are you using the Google gson library? If so you can use the JsonParser object like;
JsonElement j_element = new JsonParser().parse(YOUR_STRING);
Then you can step through the element in whatever form it's in, you can check types like element.IsJsonObject()
or element.IsJsonArray()
or whatever.
You can also turn the element into an object if is one, and do object.has("value")
then if it is a JsonObject
you can loop through the fields like;
for (Map.Entry<String, JsonElement> entry : YOUR_OBJECT.entrySet())
{
//do further bits
}
Problems to continue to parse JSON to JAVA
you can use GSON library of google. Let's try this example.
First create your java Bean (FootballPlayer.java)
FootballPlayer.java
Then you can parse your JSON to Array:
ReadJson1.java
Credits to: Github@RicardoMoya
Parse a json list into list of object Java
To achieve your goal you have to adjust your JSON as follows:
[
{
"segmentId":"Source_2021-09-01_2021-10-01",
"columns":[
"merchantRefNum",
"customerId",
"firstName"
],
"events":[
{
"event":{
"merchantRefNum":"67456456",
"customerId":"rfgvkhbj",
"firstName":"peter"
}
},
{
"event":{
"merchantRefNum":"654584856",
"customerId":null,
"firstName":"peter"
}
}
]
}
]
Notice the event fields that have been added.
Or, change your DTO, like this:
class MyClass {
private String segmentId;
private List<String> columns;
private List<Map<String, String>> events;
}
Related Topics
How to Download Image from Any Web Page in Java
How to Use Java 8 For Android Development
Android: How to Use Alarmmanager
How to Get Latitude and Longitude of the Mobile Device in Android
Gradle Finds Wrong Java_Home Even Though It's Correctly Set
What Is a Stack Trace, and How to Use It to Debug My Application Errors
How to Use Java.Util.Scanner to Correctly Read User Input from System.In and Act on It
Java Multiple File Transfer Over Socket
How to Get the Path of a Running Jar File
Why Is Processing a Sorted Array Faster Than Processing an Unsorted Array
Convert Word Doc to HTML Programmatically in Java
Android, Getting Resource Id from String
How to Write to a Folder on an Sd Card in Android
Android: Internet Connectivity Change Listener