Parsing Json Object in Java

Parsing JSON Object in Java

I'm assuming you want to store the interestKeys in a list.

Using the org.json library:

JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");

List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("interestKey"));
}

Parsing JSON data into model objects in Java

UPDATE I suggest you use JSON parser to parse the data:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

class Course {

public int _id;
public String _name;
public Teacher _teacher;

private Course(int id, String name, Teacher teacher){
this._id = id;
this._name = name;
this._teacher = teacher;
}
public Course() {

}
}

class Teacher {
public int _id;
public String _firstName;
public String _lastName;
private Teacher(int id, String fname, String lname){
this._id = id;
this._firstName = fname;
this._lastName = lname;
}
public Teacher(){

}

}

public class jsontest {

public static void main(String[] args) throws JSONException, IOException {

// String JSON_DATA = "{\n"+
// " \"courses\": [\n"+
// " { \"id\":\"998\", \"name\":\"Java Data Structures\", \"teacherId\":\"375\" },\n"+
// " { \"id\":\"999\", \"name\":\"Java Generics\", \"teacherId\":\"376\" }\n"+
// "\n"+
// " ],\n"+
// " \"teachers\": [\n"+
// " { \"id\":\"375\", \"firstName\":\"Amiyo\", \"lastName\":\"Bagchi\"},\n"+
// " { \"id\":\"376\", \"firstName\":\"Dennis\", \"lastName\":\"Ritchie\"} \n"+
// " ]\n"+
// "}\n"+
// "";
// read json file into string
String JSON_DATA = new String(Files.readAllBytes(Paths.get("path_to_json_file")), StandardCharsets.UTF_8);

// using a JSON parser
JSONObject obj = new JSONObject(JSON_DATA);
// parse "teachers" first
List<Teacher> listCourses = new ArrayList<Teacher>();
List<JSONObject> listObjs = parseJsonData(obj,"teachers");
for (JSONObject c: listObjs) {
Teacher teacher = new Teacher();
teacher._id = c.getInt("id");
teacher._firstName = c.getString("firstName");
teacher._lastName = c.getString("lastName");
listCourses.add(teacher);
}
// parse "courses" next
List<Course> resultCourses = new ArrayList<Course>();
List<JSONObject> listObjs2 = parseJsonData(obj, "courses");

for (JSONObject c: listObjs2) {
Course course = new Course();
course._id = c.getInt("id");
course._name = c.getString("name");
int teacherId = c.getInt("teacherId");
HashMap<String, Teacher> map = new HashMap<String, Teacher>();
for (Teacher t: listCourses){
map.put(Integer.toString(t._id), t);
}
course._teacher = map.get(Integer.toString(teacherId));
resultCourses.add(course);
}
}


public static List<JSONObject> parseJsonData(JSONObject obj, String pattern)throws JSONException {

List<JSONObject> listObjs = new ArrayList<JSONObject>();
JSONArray geodata = obj.getJSONArray (pattern);
for (int i = 0; i < geodata.length(); ++i) {
final JSONObject site = geodata.getJSONObject(i);
listObjs.add(site);
}
return listObjs;
}

}

Output:

Sample Image

BTW: The json data in the example has one value whose double quotes are not in pairs. To proceed, it must be fixed.

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...

Error while parsing JSON Object in Java Android

There is 4 mistakes in your code,

1.You have to check whether group has teams instead match has teams.

2.You have to get team as JSONArray instead of JSONObject because it is array.

3.You have to check the size of team, instead of find the object with key 0, there is no object with name 0 in your group,

4.You have to get the object based on index instead of key(ie., 0)

Please check the working code, this is tested

try {
JSONObject match = new JSONObject(response);
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");

if (group.has("Teams")) {
JSONArray teams = group.getJSONArray("Teams");

if (teams.length() > 0) {
JSONObject teams_object =(JSONObject) teams.get(0);
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
Log.v(TAG, team_name);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Parsing a JSONObject inside a JSONObject in a single line with json.simple

You can cast within a single line like this:

(JSONObject) ((JSONObject) YOURJSONOBJECT.get("YOUR_KEY")).get("ANOTHER_KEY");

This can get messy really quick depending on how many layers deep you have to go though

How do I parse JSON objects from a JSONArray?

Okay folks...just solved my problem. I am posting the solution in case someone runs into the same issue again, can use my solution. My solution is partly motivated by Rahul Rabhadiya. Thanks, dude.

try{
row=br.readLine();
JSONArray root = (JSONArray) JSONValue.parseWithException(row);

for (int i=0;i<root.size();i++)
{

JSONObject rootObj = (JSONObject) root.get(i);
String fullname=(String) rootObj.get("fullname");

System.out.println (fullname);
}
}catch(Exception e)
{
e.printStackTrace();
}

Error Parsing JSON String to JSONObject in Java

I found my problem.

The String I was processing was malformed for the source. Fixing the string was the answer in here. Nothing was wrong with how I parsed the string.

Thanks for all the answers and the help.



Related Topics



Leave a reply



Submit