There are lots of API's and libraries are present but I prefer to use org.json API suggested by json.org
you can also go for GSON library which is one of the best library for serialize and deserialize Java objects to (and from) JSON.
here's the quick demo of reading above JSON with org.json API.
import org.json.JSONObject;
import org.json.JSONArray;
public class HelloWorld {
public static void main(String[] args) {
String jsonString = "[ { \"name\": \"Andrew\", \"age\": 21, \"parents\": [ { \"name\": \"Joseph\", \"age\": 18 }, { \"name\": \"Joseph\", \"age\": 18 } ] }, { \"name\": \"Maria\", \"age\": 35, \"parents\": [ { \"name\": \"Kassandra\", \"age\": 16 }, { \"name\": \"Abigail\", \"age\": 22 } ] } ]";
JSONArray json = new JSONArray(jsonString);
for(int i=0; i<json.length(); i++){
JSONObject j = json.getJSONObject(i);
System.out.println(j + "\n------");
}
}
}
Answer from Kishor Mandve on Stack OverflowThere are lots of API's and libraries are present but I prefer to use org.json API suggested by json.org
you can also go for GSON library which is one of the best library for serialize and deserialize Java objects to (and from) JSON.
here's the quick demo of reading above JSON with org.json API.
import org.json.JSONObject;
import org.json.JSONArray;
public class HelloWorld {
public static void main(String[] args) {
String jsonString = "[ { \"name\": \"Andrew\", \"age\": 21, \"parents\": [ { \"name\": \"Joseph\", \"age\": 18 }, { \"name\": \"Joseph\", \"age\": 18 } ] }, { \"name\": \"Maria\", \"age\": 35, \"parents\": [ { \"name\": \"Kassandra\", \"age\": 16 }, { \"name\": \"Abigail\", \"age\": 22 } ] } ]";
JSONArray json = new JSONArray(jsonString);
for(int i=0; i<json.length(); i++){
JSONObject j = json.getJSONObject(i);
System.out.println(j + "\n------");
}
}
}
Use jackson library. Here is a snippet.
public static void main(final String[] args) throws JsonProcessingException {
final List<Child> children = new ObjectMapper().readValue(
readFromFile("data.json"), new TypeReference<List<Child>>() {
});
System.out.println(children);
}
public static String readFromFile(final String resourcePath) {
final ClassPathResource resource = new ClassPathResource(resourcePath);
try {
final InputStream inputStream = resource.getInputStream();
return readFromInputStream(inputStream);
} catch (final IOException var4) {
return "";
}
}
private static String readFromInputStream(final InputStream inputStream) throws IOException {
final StringBuilder resultStringBuilder = new StringBuilder();
final BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
Throwable var3 = null;
try {
String line;
try {
while ((line = br.readLine()) != null) {
resultStringBuilder.append(line).append("\n");
}
} catch (final Throwable var12) {
var3 = var12;
throw var12;
}
} finally {
if (br != null) {
if (var3 != null) {
try {
br.close();
} catch (final Throwable var11) {
var3.addSuppressed(var11);
}
} else {
br.close();
}
}
}
return resultStringBuilder.toString();
}
You can use the below methods to read from a file and convert the JSON array to a List of Questions.
public String readJsonFromFile(String filePath) throws IOException, ParseException {
String json = Files.readString(Paths.get("file path"));
return new JSONParser().parse(json).toString();
}
public List<Question> convert(String JsonString) throws JsonMappingException, JsonProcessingException {
ObjectMapper om = new ObjectMapper();
CollectionType typeReference =
TypeFactory.defaultInstance().constructCollectionType(List.class, Question.class);
List<Question> questions = om.readValue(JsonString, typeReference);
return questions;
}
If your JSON keys and Java class fields are different, use @JsonPropery annotation to map keys to fields
import com.fasterxml.jackson.annotation.JsonProperty;
public class Question {
@JsonProperty("question")
private String title;
@JsonProperty("answer 1")
private String a1;
@JsonProperty("answer 2")
private String a2;
@JsonProperty("answer 3")
private String a3;
@JsonProperty("correct answer")
private String cA;
//setters & getters
}
Required Jars:
jackson-annotations.jar
jackson-core.jar
jackson-databind.jar
json-simple.jar //used to parse Json file to String
You have two steps
Get JSON string from the file, use read file from assets
Extract items from the JSON string use How do I convert a JSON array into a Java List. I'm using svenson
How to convert JSON string into List of Java object? - Stack Overflow
How to read JSON file of objects into a list in Java with Jackson - Stack Overflow
Getting JSON File from resources and reading to a List of Java Objects - Stack Overflow
How to read json file into java with simple JSON library - Stack Overflow
You are asking Jackson to parse a StudentList. Tell it to parse a List (of students) instead. Since List is generic you will typically use a TypeReference
List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
For any one who looks for answer yet:
1.Add jackson-databind library to your build tools like Gradle or Maven
2.in your Code:
ObjectMapper mapper = new ObjectMapper();
List<Student> studentList = new ArrayList<>();
studentList = Arrays.asList(mapper.readValue(jsonStringArray, Student[].class));
The whole file is an array and there are objects and other arrays (e.g. cars) in the whole array of the file.
As you say, the outermost layer of your JSON blob is an array. Therefore, your parser will return a JSONArray. You can then get JSONObjects from the array ...
JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"));
for (Object o : a)
{
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
String city = (String) person.get("city");
System.out.println(city);
String job = (String) person.get("job");
System.out.println(job);
JSONArray cars = (JSONArray) person.get("cars");
for (Object c : cars)
{
System.out.println(c+"");
}
}
For reference, see "Example 1" on the json-simple decoding example page.
You can use jackson library and simply use these 3 lines to convert your json file to Java Object.
ObjectMapper mapper = new ObjectMapper();
InputStream is = Test.class.getResourceAsStream("/test.json");
testObj = mapper.readValue(is, Test.class);
This is a working example based (and tested) with gson-2.8.0. It accepts an arbitrary sequence of JSON objects on a given input stream. And, of course, it does not impose any restrictions on how you have formatted your input:
InputStream is = /* whatever */
Reader r = new InputStreamReader(is, "UTF-8");
Gson gson = new GsonBuilder().create();
JsonStreamParser p = new JsonStreamParser(r);
while (p.hasNext()) {
JsonElement e = p.next();
if (e.isJsonObject()) {
Map m = gson.fromJson(e, Map.class);
/* do something useful with JSON object .. */
}
/* handle other JSON data structures */
}
I know it has been almost one year for this post :) but i am actually reposing again as an answer because i had this problem same as you Yuan
I have this text.txt file - I know this is not a valid Json array - but if you look, you will see that each line of this file is a Json object in its case alone.
{"Sensor_ID":"874233","Date":"Apr 29,2016 08:49:58 Info Log1"}
{"Sensor_ID":"34234","Date":"Apr 29,2016 08:49:58 Info Log12"}
{"Sensor_ID":"56785","Date":"Apr 29,2016 08:49:58 Info Log13"}
{"Sensor_ID":"235657","Date":"Apr 29,2016 08:49:58 Info Log14"}
{"Sensor_ID":"568678","Date":"Apr 29,2016 08:49:58 Info Log15"}
Now I want to read each line of the above and parse the names "Sensor_ID" and "Date" into Json format. After long search, I have the following:
Try it and look on the console to see the result. I hope it helps.
package reading_file;
import java.io.*;
import java.util.ArrayList;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class file_read {
public static void main(String [] args) {
ArrayList<JSONObject> json=new ArrayList<JSONObject>();
JSONObject obj;
// The name of the file to open.
String fileName = "C:\\Users\\aawad\\workspace\\kura_juno\\data_logger\\log\\Apr_28_2016\\test.txt ";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
obj = (JSONObject) new JSONParser().parse(line);
json.add(obj);
System.out.println((String)obj.get("Sensor_ID")+":"+
(String)obj.get("Date"));
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}