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
How to read json string in java?
Jackson or GSON are popular libraries for converting JSON strings to objects or maps.
Jackson example:
String json = "[{\"foo\": \"bar\"},{\"foo\": \"biz\"}]";
JsonFactory f = new JsonFactory();
JsonParser jp = f.createJsonParser(json);
// advance stream to START_ARRAY first:
jp.nextToken();
// and then each time, advance to opening START_OBJECT
while (jp.nextToken() == JsonToken.START_OBJECT)) {
Foo foobar = mapper.readValue(jp, Foo.class);
// process
// after binding, stream points to closing END_OBJECT
}
public class Foo {
public String foo;
}
How to convert jsonString to JSONObject in Java
Using org.json library:
try {
JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
}catch (JSONException err){
Log.d("Error", err.toString());
}
How to parse a List inside a Json String In java?
import org.json.*;
String jsonString = inputJsonString; //assign your JSON String here
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("predicted_route");
ArrayList<String> arrayList = new ArrayList<String>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
arrayList.add(jsonArray.getString(i));
}
}
More examples to parse JSON in Java
Downloadable jar: http://mvnrepository.com/artifact/org.json/json
How to parse a part of JSON message to String and pass it to another class?
If it's guarantied that your string only contains one "Message" tag you could try getting the index of that and parsing the string that follows (for efficiency not building the whole string):
while ((msg = rdr.readLine()) != null) {
int i = msg.indexOf("\"Message\":");
// If not contained, continue with next line
if (i == -1)
continue;
i += 10; // Add length of searched string to reach end of match
// Skip all whitespace
while (Character.isWhitespace(msg.charAt(i)))
i++;
// If following is a string
if (msg.charAt(i++) == '"') {
StringBuilder sb = new StringBuilder();
char c;
// While not reached end of string
for (; (c = msg.charAt(i)) != '"'; i++) {
// For escaped quotes and backslashes; could be made a lot simpler without
if (c == '\\')
sb.append(msg.charAt(++i));
else sb.append(c);
}
messageString = sb.toString();
}
}
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...
Related Topics
How to Solve the Lazyinitializationexception When Using JPA and Hibernate
Calling a Mapreduce Job from a Simple Java Program
Calculate the Display Width of a String in Java
Detect and Extract Url from a String
Read File from Resources Folder in Spring Boot
How to Write a Basic Swap Function in Java
Dealing with an Arraystoreexception
How to Convert Current Date into String in Java
Does Calling Clone() on an Array Also Clone Its Contents
Hibernate - @Elementcollection - Strange Delete/Insert Behavior
Converting Characters to Integers in Java
Sending Email via Gmail Smtp Server in Java
Calculating Difference in Dates in Java
Dependency Injection in Struts2 Accessing Session Scoped Beans
Why Does Sun.Misc.Unsafe Exist, and How Can It Be Used in the Real World