I have a json file formatted as the following:
[{
'title': 'Java',
'authors': ['Auth', 'Name']
},
{
'title': 'Java2',
'authors': ['Auth2', 'Name2']
},
{
'title': 'Java3',
'authors': ['Auth3', 'Name3']
}]
So i've tried using gson library to parse the file, with the following code:
JsonElement jelement = new JsonParser().parse(pathFile);
JsonObject jObject = jelement.getAsJsonObject();
JsonArray jOb = jObject.getAsJsonArray("");
final String[] jObTE = new String[jOb.size()];
for (int k=0; k<jObTE.length; k++) {
final JsonElement jCT = jOb.get(k);
JsonObject jOTE = jCT.getAsJsonObject();
JsonArray jContentTime = jOTE.getAsJsonArray("content_time");
final String[] contentTime = new String[jContentTime.size()];
for (int i=0; i<contentTime.length; i++) {
final JsonElement jsonCT = jContentTime.get(i);
JsonObject jObjectTE = jsonCT.getAsJsonObject();
JsonArray jTE = jObjectTE.getAsJsonArray("");
final String[] contentTimeTE = new String[jTE.size()];
for (int j=0; j<contentTimeTE.length; j++) {
final JsonElement jsonCTTE = jTE.get(j);
contentTime[j] = jsonCTTE.getAsString();
}
}
}
But, in doing so, i found this error: java.lang.IllegalStateException: Not a JSON Object at the second line.
You're trying to parse array to object, in which case you'll fail, because top level structure in your json is array.
I would parse this JSON in slightly different way
1) Create some Model class
public class Model {
private String title;
private List<String> authors;
//getters ...
}
2) Parse your JSON (
public static final String JSON_PATH = "/Users/dawid/Workspace/Test/test.json";
Gson gson = new Gson();
BufferedReader br = new BufferedReader(new FileReader(JSON_PATH));
Type type = new TypeToken<List<Model>>(){}.getType();
List<Model> models = gson.fromJson(br, type);
Your code is barely readable, so i guess that solved your problem
Second way:
BufferedReader br = new BufferedReader(new FileReader(JSON_PATH));
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(br).getAsJsonArray();
Related
Hello I have a JSF application that makes a GET Request to an API gets a JSON and from that JSON gets an elements and fills a JSF Datatable with it. I would like to fill the datatable with all elements but only one gets added.
This is my Java code :
#ManagedBean(name = "logic", eager = true)
#SessionScoped
public class Logic {
static JSONObject jsonObject = null;
static JSONObject jo = null;
static JSONArray cat = null;
private ArrayList<Logic> logics;
StringBuilder sb = new StringBuilder();
String cif2;
public void connect() {
try {
URL url = new URL("xxx");
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while((inputLine = in.readLine())!= null){
System.out.println(inputLine);
sb.append(inputLine+"\n");
in.close();
}
} catch(Exception e) {System.out.println(e);}
}
private String cif;
public ArrayList<Logic> getLogics() {
return logics;
}
public Logic() throws ParseException {
connect();
JSONParser parser = new JSONParser();
jsonObject = (JSONObject) parser.parse(sb.toString());
cat = (JSONArray) jsonObject.get("mesaje");
for(int i = 0; i < cat.size(); i++) {
jo = (JSONObject) cat.get(i);
cif2 = jo.get("cif").toString();
logics = new ArrayList<Logic>(Arrays.asList(new Logic(cif2)));
}
}
public Logic(String cif) throws ParseException {
this.cif = cif;
}
public String getCif() {
return cif;
}
public void setCif(String cif) {
this.cif = cif;
}
}
The code that I wrote to make the insertion is this:
public Logic() throws ParseException {
connect();
JSONParser parser = new JSONParser();
jsonObject = (JSONObject) parser.parse(sb.toString());
cat = (JSONArray) jsonObject.get("mesaje");
for(int i = 0; i < cat.size(); i++) {
jo = (JSONObject) cat.get(i);
cif2 = jo.get("cif").toString();
logics = new ArrayList<Logic>(Arrays.asList(new Logic(cif2)));
}
}
It does a for loop over the json but it only adds the last value.
I would like to add all values
Thanks in advance
You should initialise the logics with empty arraylist.
private ArrayList<Logic> logics = new ArrayList<>();
And
Replace logics = new ArrayList<Logic>(Arrays.asList(new Logic(cif2))); with logics.add(new Logic(cif2));
I think this line is the culprit
logics = new ArrayList<Logic>(Arrays.asList(new Logic(cif2)));
As you can see, it will create new instance of the logics everytime the loop iterates instead of adding/append the parsed value to the list. you should create a variable to accept data, then append/add it something like:
logics.append( new ArrayList<Logic>(Arrays.asList(new Logic(cif2))) );
Are you using jackson-core-2.9.6? You might want to use ObjectMapper rather than using JSONParser.
You might want to convert this lines of code
JSONParser parser = new JSONParser();
jsonObject = (JSONObject) parser.parse(sb.toString());
cat = (JSONArray) jsonObject.get("mesaje");
for(int i = 0; i < cat.size(); i++) {
jo = (JSONObject) cat.get(i);
cif2 = jo.get("cif").toString();
logics = new ArrayList<Logic>(Arrays.asList(new Logic(cif2)));
}
to
ObjectMapper objectMapper = new ObjectMapper();//Create the ObjectMapper
// readValue accepts 2 param. string to be converted, and Object class/type to be used on mapping the data.
logics = objectMapper.readValue(sb.toString(), new TypeReference<List<Logic>>(){});
//If you have a adapter class to handle the entire JSON Record, you can use it to replace Logic.
It is much simpler to read and use.
PS: I notice that you are retrieving data from a larger set of JSON. If that is the case, you should have an adapter/bridge/help (whatever you want to call that) class to accept/map that JSON rather than using the same class. Inside that adapter class, you can add a method to extract data, list, and other things you want to get from the JSON record.
//Make sure you have correct attribute as to the JSON you are going to map in this object
class JSONReceived{
private . . . // attributes of the JSON
//getters and setters
public List<Mesaje> getMesajeList(){
//do your stuff here
}
}
Then you can use these lines instead of earlier lines of codes.
ObjectMapper objectMapper = new ObjectMapper();//Create the ObjectMapper
JSONReceived json = objectMapper.readValue(sb.toString(), JSONReceived.class);
logics = json. getMesajeList();
That way, it will help you find bug in record size and other related problems.
I'm trying to extract data from Github Sample Collection of Books but i am getting a blank screen. here is my JSON parsing code.
try {
JSONObject bookObject = new JSONObject(SAMPLE);
JSONArray booksArray = bookObject.getJSONArray("books");
for (int i = 0; i < booksArray.length(); i++){
JSONObject currentBook = booksArray.getJSONObject(i);
String title = currentBook.getString("title");
String author = currentBook.getString("author");
String isbn = currentBook.getString("isbn");
Book book = new Book(title,author,isbn);
books.add(book);
}
}catch (JSONException e){
Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
}
I recommend to you use GSON, is very easy library
To Json
Gson gson = new Gson();
Staff obj = new Staff();
// 1. Java object to JSON file
gson.toJson(obj, new FileWriter("C:\\projects\\staff.json"));
// 2. Java object to JSON string
String jsonInString = gson.toJson(obj);
From Json
Gson gson = new Gson();
// 1. JSON file to Java object
Staff staff = gson.fromJson(new FileReader("C:\\projects\\staff.json"), Staff.class);
// 2. JSON string to Java object
String json = "{'name' : 'mkyong'}";
Staff staff = gson.fromJson(json, Staff.class);
// 3. JSON file to JsonElement, later String
JsonElement json = gson.fromJson(new FileReader("C:\\projects\\staff.json"), JsonElement.class);
String result = gson.toJson(json);
If you want to see more information about this you can check this link: https://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
Try this :
Gson gson = new Gson();
JSONObject o = new JSONObject(jsonData.toString()); // pass your data here
JSONArray arr = new JSONArray(o.get("books").toString());
List<Book> books = new ArrayList<Book>();
for (int i = 0; i < arr.length(); i++) {
Book book = gson.fromJson(arr.get(i).toString(), Book.class);
books.add(book);
}
I have used Gson library here.
There are other libraries as well.
Refer this link for more details: http://tutorials.jenkov.com/java-json/gson-jsonparser.html
you need to convert the response from the network service to string and then get the jsonArray it will work
Like this ::
#Override
public void onResponse(Call call, final okhttp3.Response response) throws IOException {
final String stringResponse = response.body().string();
//insted of sample pass the stringresponse it will work
JSONObject bookObject = new JSONObject(stringResponse);
JSONArray booksArray = bookObject.getJSONArray("books");
for (int i = 0; i < booksArray.length(); i++){
JSONObject currentBook = booksArray.getJSONObject(i);
String title = currentBook.getString("title");
String author = currentBook.getString("author");
String isbn = currentBook.getString("isbn");
Book book = new Book(title,author,isbn);
books.add(book);
}
});
Check your model class , in that you set the parameters.
I have this code where "Ocupacion" is object class that have another atribute objects. (since is a large class i don't post all the atributes of the class)
public String genHor(){
Collection<Ocupacion> ocupas = new ArrayList<>();
ocupas= H.makeOcupacion();
Gson gson = new Gson();
return gson.toJson(ocupas);
}
Then in another class where i recive the json String and i want to parse it. I do that:
public void assig(String json){
JsonObject obj = new JsonParser().parse(json).getAsJsonObject();
}
Then i get the java.lang.IllegalStateException: Not a JSON Object
String json is like that:
[{"sesionConcreta":{"grup":{"NumGr":10,"TamGr":200,"subgrupo":[{"NumSub":11,"TamSub":200}],"asignatura":"prop"},"sessio":{"HorasSes":2,"TipoSes":"TEORIA"}},"aula":{"NomAu":"a5105","Capacidad":200,"Tipo":"lab"},"diayHora":{"Dia":"L","Hora":8}}]
[{"sesionConcreta":{"grup":{"NumGr":10,"TamGr":200,"subgrupo":[{"NumSub":11,"TamSub":200}],"asignatura":"prop"},"sessio":{"HorasSes":2,"TipoSes":"TEORIA"}},"aula":{"NomAu":"a5105","Capacidad":200,"Tipo":"lab"},"diayHora":{"Dia":"L","Hora":8}}]
it is a json array not a json object because it is in [] not in {}:
JsonArray jsonArr = new JsonParser().parse(json).getAsJsonArray();
JsonObject obj = jsonArr.get(0).getAsJsonObject();
JsonObject sesionConcretaObj = obj.get("sesionConcreta").getAsJsonObject();
JsonObject groupObj = sesionConcretaObj.get("grup").getAsJsonObject();
int numGr = groupObj.get("NumGr").getAsInt();
The jsonString is actually a jsonArray not a jsonObject. Try with below:
String jsonStr = "[{\"sesionConcreta\":{\"grup\":{\"NumGr\":10,\"TamGr\":200,\"subgrupo\":[{\"NumSub\":11,\"TamSub\":200}],\"asignatura\":\"prop\"},\"sessio\":{\"HorasSes\":2,\"TipoSes\":\"TEORIA\"}},\"aula\":{\"NomAu\":\"a5105\",\"Capacidad\":200,\"Tipo\":\"lab\"},\"diayHora\":{\"Dia\":\"L\",\"Hora\":8}}]";
JSONArray jsonarray = new JSONArray(jsonStr);
for(int i = 0; i< jsonarray.length(); i++) {
JSONObject sesionConcreta = (JSONObject)jsonarray.getJSONObject(i).get("sesionConcreta");
JSONObject grup = (JSONObject)sesionConcreta.get("grup");
System.out.println(grup.get("NumGr"));
}
try this one:
public static void assig(String json){
Gson gson = new Gson();
Ocupacion[] occs = gson.fromJson(json, Ocupacion[].class);
System.out.println(occs);
}
This is what I have to read text in JSON format from a website. But i get the error
Java.lang.ClassCastException: org.json.simple.JSONObject cannot be
cast to org.json.simple.JSONArray
This is driving me nuts. Can anyone help? I also need to check this string for all instances of "Username" and run something for each of them.
public class CommandCheck implements CommandExecutor {
private String username;
private static String host = "example.com";
private URL url;
private String apiKey = main.getNode("API-KEY");
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] arg3) {
try {
this.url = new URL(CommandCheck.host);
final URLConnection conn = this.url.openConnection();
conn.setConnectTimeout(5000);
if (this.apiKey != null) {
conn.addRequestProperty("x-api-key", this.apiKey);
}
conn.addRequestProperty("User-Agent", main.USER_AGENT);
conn.setDoOutput(true);
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final String response = reader.readLine();
sender.sendMessage(response); //Im just dumping the raw String for the person running the command to see Debug mostly
final JSONArray array = (JSONArray) JSONValue.parse(response);
if (array.isEmpty()) {
sender.sendMessage("The Array appears to be empty");
return false;
}
JSONObject latestUpdate = (JSONObject) array.get(array.size() - 1);
username = (String) latestUpdate.get("Username");
sender.sendMessage("whitelist add" + username);
return true;
} catch (final IOException e) {
if (e.getMessage().contains("HTTP response code: 403")) {
sender.sendMessage("I think there is an API key issue");
} else {
sender.sendMessage("Problem of unknown orign");
}
return false;
}
}
Try changing the following line:
final JSONArray array = (JSONArray) JSONValue.parse(response);
to:
final JSONObject jsObj = (JSONObject) JSONValue.parse(response);
Can you provide the JSON String you are trying to parse? I.e. the value of response?
JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class)));
JsonArray jsonArray = jsonReader.readArray();
ListIterator l = jsonArray.listIterator();
while ( l.hasNext() ) {
JsonObject j = (JsonObject)l.next();
JsonObject ciAttr = j.getJsonObject("ciAttributes") ;
org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray means that you are trying to convert the json object into the json array. if your response in the json object as a response then you first need it to convert in the Json object.
after converting you can get the the Json array from the json object using the get("key-name")
JSONObject resObj = new JSONObject(responseString);
JSONArray resArray = resObj.getJSONArray("Username");
for (int i=0; i<resArray.length(); i++)
String resultString = resArray.getString(i);
it gives you all usersname.
i think this code helps you to solve your problem.
I have a trouble finding a way how to parse JSONArray.
It looks like this:
[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
I know how to parse it if the JSON was written differently (In other words, if I had json object returned instead of an array of objects).
But it's all I have and have to go with it.
*EDIT: It is a valid json. I made an iPhone app using this json, now I need to do it for Android and cannot figure it out.
There are a lot of examples out there, but they are all JSONObject related. I need something for JSONArray.
Can somebody please give me some hint, or a tutorial or an example?
Much appreciated !
use the following snippet to parse the JsonArray.
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
I'll just give a little Jackson example:
First create a data holder which has the fields from JSON string
// imports
// ...
#JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
#JsonProperty("name")
public String mName;
#JsonProperty("url")
public String mUrl;
}
And parse list of MyDataHolders
String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString,
new TypeReference<ArrayList<MyDataHolder>>() {});
Using list items
String firstName = list.get(0).mName;
String secondName = list.get(1).mName;
public static void main(String[] args) throws JSONException {
String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";
JSONArray jsonarray = new JSONArray(str);
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("name");
String url = obj.getString("url");
System.out.println(name);
System.out.println(url);
}
}
Output:
name1
url1
name2
url2
Create a class to hold the objects.
public class Person{
private String name;
private String url;
//Get & Set methods for each field
}
Then deserialize as follows:
Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String
Reference Article: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/
In this example there are several objects inside one json array. That is,
This is the json array: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
This is one object: {"name":"name1","url":"url1"}
Assuming that you have got the result to a String variable called jSonResultString:
JSONArray arr = new JSONArray(jSonResultString);
//loop through each object
for (int i=0; i<arr.length(); i++){
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("url");
}
public class CustomerInfo
{
#SerializedName("customerid")
public String customerid;
#SerializedName("picture")
public String picture;
#SerializedName("location")
public String location;
public CustomerInfo()
{}
}
And when you get the result; parse like this
List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());
A few great suggestions are already mentioned.
Using GSON is really handy indeed, and to make life even easier you can try this website
It's called jsonschema2pojo and does exactly that:
You give it your json and it generates a java object that can paste in your project.
You can select GSON to annotate your variables, so extracting the object from your json gets even easier!
My case
Load From Server Example..
int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
if (jsonLength != 1) {
for (int i = 0; i < jsonLength; i++) {
JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
JSONObject resJson = (JSONObject) jsonArray.get(i);
//addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
}
Create a POJO Java Class for the objects in the list like so:
class NameUrlClass{
private String name;
private String url;
//Constructor
public NameUrlClass(String name,String url){
this.name = name;
this.url = url;
}
}
Now simply create a List of NameUrlClass and initialize it to an ArrayList like so:
List<NameUrlClass> obj = new ArrayList<NameUrlClass>;
You can use store the JSON array in this object
obj = JSONArray;//[{"name":"name1","url":"url1"}{"name":"name2","url":"url2"},...]
Old post I know, but unless I've misunderstood the question, this should do the trick:
s = '[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"}]';
eval("array=" + s);
for (var i = 0; i < array.length; i++) {
for (var index in array[i]) {
alert(array[i][index]);
}
}
URL url = new URL("your URL");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
//setting the json string
String finalJson = buffer.toString();
//this is your string get the pattern from buffer.
JSONArray jsonarray = new JSONArray(finalJson);