working solution
JSONParser parser = new JSONParser();
JSONObject jsonObject;
try {
jsonObject = (JSONObject) parser.parse(new FileReader("E:\\json.txt"));
out.println("<br>"+jsonObject);
JSONArray from_excel = (JSONArray)jsonObject.get("from_excel");
// for row output 1
for(Object o: from_excel){
out.println("<br>"+o);
}
// for row output 2
Iterator iterator = from_excel.iterator();
while (iterator.hasNext()) {
out.println("<br>"+iterator.next());
}
// for item output 3
for (int i = 0; i < from_excel.size(); i++) {
JSONObject jsonObjectRow = (JSONObject) from_excel.get(i);
String num = (String) jsonObjectRow.get("num");
String solution = (String) jsonObjectRow.get("solution");
out.println("<br>num="+num+"; solution="+solution);
}
} catch (Exception e) {
out.println("Error: "+e);
}
Answer from Nikolay Baranenko on Stack Overflowworking solution
JSONParser parser = new JSONParser();
JSONObject jsonObject;
try {
jsonObject = (JSONObject) parser.parse(new FileReader("E:\\json.txt"));
out.println("<br>"+jsonObject);
JSONArray from_excel = (JSONArray)jsonObject.get("from_excel");
// for row output 1
for(Object o: from_excel){
out.println("<br>"+o);
}
// for row output 2
Iterator iterator = from_excel.iterator();
while (iterator.hasNext()) {
out.println("<br>"+iterator.next());
}
// for item output 3
for (int i = 0; i < from_excel.size(); i++) {
JSONObject jsonObjectRow = (JSONObject) from_excel.get(i);
String num = (String) jsonObjectRow.get("num");
String solution = (String) jsonObjectRow.get("solution");
out.println("<br>num="+num+"; solution="+solution);
}
} catch (Exception e) {
out.println("Error: "+e);
}
There is no "solution" array in the JSON. "from_excel" is the array. So your code should look like this :
Object obj = parser.parse(new FileReader("E:\\json.txt"));
JSONObject jsonObject = (JSONObject) obj;
out.println(jsonObject.get("from_excel"));
JSONArray solutions = (JSONArray) jsonObject.get("from_excel");
Iterator iterator = solutions.iterator();
while (iterator.hasNext()) {
out.println(iterator.next());
}
Use this for get json value in string format from file
public String loadJSONFromFile() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
JsonObject is a child of a JsonArray, so as per my suggestion use like this
final JSONArray jsonArray = new JSONArray();
jsonArray.put(obj); //obj is your JsonObject
and you can get JsonObject from array like
jsonArray.getJSONObject(0); //0 is index of your JsonObject in JsonArray
Hope this help you.
Check the content of the file.
It seems that the content is not an array, but a json object.
Open the file with a text editor. If the content is something like:
{ // First character
... content here
} // Last character
it is an object, if it is similar to
[ // First character
... content here
] // Last character
it is an array.
If you need to read an object you need to change your code as follow:
JSONObject jsonObject = (JSONObject) obj;
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);
Create a POJO class to represent your JSON data:
public class CarInfo { String car; String colour; String qty; String date_manufactured; }Use GSON to parse JSON String Array
String carInfoJson = "[{ \"car\": \"Toyota\", \"colour\": \"red\",\"qty\": \"1\",\"date_manufactured\":\"12972632260006\" }, { \"car\":\"Hyundai\", \"colour\":\"red\",\"qty\":\"2\",\"date_manufactured\":\"1360421626000\" }]"; Gson gson = new Gson(); CarInfo[] carInfoArray = gson.fromJson(carInfoJson, CarInfo[].class);Use GSON to parse JSON String Array from a file
String carInfoJson= new String(Files.readAllBytes(Paths.get("filename.txt"))); Gson gson = new Gson(); CarInfo[] carInfoArray = gson.fromJson(carInfoJson, CarInfo[].class);Use GSON to parse JSON String Array from a file using BufferedReader
BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); Gson gson = new Gson(); CarInfo[] carInfoArray = gson.fromJson(reader, CarInfo[].class); } catch (FileNotFoundException ex) { ... } finally { ... }Use GSON to parse JSON String Array from a file using JsonReader in stream mode
try { InputStream stream = new FileInputStream("c:\\filename.txt"); JsonReader reader = new JsonReader(new InputStreamReader(stream, "UTF-8")); Gson gson = new Gson(); // Read file in stream mode reader.beginArray(); while (reader.hasNext()) { CarInfo carInfo = gson.fromJson(reader, CarInfo.class); } reader.endArray(); reader.close(); } catch (UnsupportedEncodingException ex) { ... } catch (IOException ex) { ... }
I'm using json-simple to explain how to do this. Your json is a JSONArray (because it starts and ends with square brackets) with JSONObject (curly brackets with pair list) inside so first you've to extract the array using a JSONParser and then you can easily iterate over it and get fields from each JSONObject.
Here is a simple example it just shows you an easy and understandable way:
String json = "[{ \"car\": \"Toyota\", \"colour\": \"red\", \"qty\": \"1\",\"date_manufactured\":\"12972632260006\" }, { \"car\": \"Hyundai\", \"colour\": \"red\", \"qty\": \"2\",\"date_manufactured\":\"1360421626000\" }]";
JSONParser parser = new JSONParser();
try {
/* It's a JSONArray first. */
JSONArray tmpArr = (JSONArray)parser.parse(json);
for(Object obj : tmpArr){
/* Extract each JSONObject */
JSONObject tmpObj = (JSONObject) obj;
System.out.println(tmpObj.get("car"));
System.out.println(tmpObj.get("colour"));
System.out.println(tmpObj.get("qty"));
System.out.println(tmpObj.get("date_manufactured"));
}
} catch (ParseException e) {
e.printStackTrace();
}
Note that you can use Gson, it's much more complete then json-simple but a little bit trickier.
You can use gson library
You can use Maven or jar file: http://mvnrepository.com/artifact/com.google.code.gson/gson
package com.test;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class AppJsonTest {
public static void main(String[] args) {
List<DataObject> objList = new ArrayList<DataObject>();
objList.add(new DataObject(1, "Coca Cola", 0.9, 19));
objList.add(new DataObject(2, "Coca Cola Zero", 0.6, 19));
// Convert the object to a JSON string
String json = new Gson().toJson(objList);
System.out.println(json);
// Now convert the JSON string back to your java object
Type type = new TypeToken<List<DataObject>>() {
}.getType();
List<DataObject> inpList = new Gson().fromJson(json, type);
for (int i = 0; i < inpList.size(); i++) {
DataObject x = inpList.get(i);
System.out.println(x.toString());
}
}
}
class DataObject {
int idProducto;
String Nombre;
Double Precio;
int Cantidad;
public DataObject(int idProducto, String nombre, Double precio, int cantidad) {
this.idProducto = idProducto;
Nombre = nombre;
Precio = precio;
Cantidad = cantidad;
}
public int getIdProducto() {
return idProducto;
}
public void setIdProducto(int idProducto) {
this.idProducto = idProducto;
}
public String getNombre() {
return Nombre;
}
public void setNombre(String nombre) {
Nombre = nombre;
}
public Double getPrecio() {
return Precio;
}
public void setPrecio(Double precio) {
Precio = precio;
}
public int getCantidad() {
return Cantidad;
}
public void setCantidad(int cantidad) {
Cantidad = cantidad;
}
@Override
public String toString() {
return "DataObject [idProducto=" + idProducto + ", Nombre=" + Nombre + ", Precio=" + Precio + ", Cantidad=" + Cantidad + "]";
}
}
Use gson library to read and write json:
try {
JsonReader reader = new JsonReader(new FileReader("json_file_path.json"));
reader.beginArray();
while (reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("idProducto")) {
System.out.println(reader.nextInt());
} else if (name.equals("Nombre")) {
System.out.println(reader.nextString());
} else if (name.equals("Precio")) {
System.out.println(reader.nextDouble());
} else if (name.equals("Cantidad")) {
System.out.println(reader.nextInt());
} else {
reader.skipValue();
}
}
reader.endObject();
}
reader.endArray();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
download http://www.java2s.com/Code/JarDownload/gson/gson-2.2.2.jar.zip
You could use this library:
http://www.json.org/java/
Then you can read the file into a String used a BufferedReader, close the reader and do something like this:
JSONArray ja = new JSONOArray(string);
int[][] result = new int[ja.length()][];
for (int i = 0; i < ja.length(); i++) {
JSONAarray ja2 = ja.getJSONArray(i);
result[i] = new int[ja2.length()];
for (int j = 0; j < ja2.length(); j++) {
result[i][j]=ja2.getInt(j);
}
}
I haven't tested this code, and you also might want to add some error checking and extract local variables, depending on how sure you are the file is in the right format. This does not assume your file contains a rectangular matrix.
If you have JSON as input and want to convert it to a Java 2D array you can easily convert your JSON input using the Jackson library. Jackson can convert JSON to POJOs and POJOs to JSON and this is called deserialization/serialization.
The main class used for mapping between JSON and POJOs is the ObjectMapper. To convert from a JSON String to a 2D array of ints the following Java code can be used:
final String json = "[[1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]";
// Create a Jackson mapper
ObjectMapper mapper = new ObjectMapper();
// Map the JSON to a 2D array
final int[][] ints = mapper.readValue(json, int[][].class);
The only dependencies required to run Jackson is:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version> <!-- At the time of writing -->
</dependency>