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.
strResponse = {"GetCitiesResult":["1-Vizag","2-Hyderbad","3-Pune","4-Chennai","9-123","11-Rohatash","12-gopi","13-Rohatash","14-Rohatash","10-123"]}
JSONObject json = new JSONObject(strResponse);
// get LL json object
String json_LL = json.getJSONObject("GetCitiesResult").toString();
Now i want to convert the json string to List in andriod
Please make sure your response String is correct format, if it is, then try this:
try {
ArrayList<String> list = new ArrayList<String>();
JSONObject json = new JSONObject(strResponse);
JSONArray array = json.getJSONArray("GetCitiesResult");
for (int i = 0; i < array.length(); i++) {
list.add(array.getString(i));
}
} catch (Exception e) {
e.printStackTrace();
}
Simply using Gson library you can convert json response to pojo class.
Copy the json string to create pojo structure using this link: http://www.jsonschema2pojo.org/
Gson gson = new Gson();
GetCitiesResult citiesResult = gson.fromJson(responseString, GetCitiesResult.class);
It will give the GetCitiesResult object inside that object you get a list of your response like
public List<String> getGetCitiesResult() {
return getCitiesResult;
}
Call only citiesResult.getGetCitiesResult(); it will give a list of cities.
You can also use this library com.squareup.retrofit2:converter-gson:2.1.0
This piece of code did the trick
List<String> list3 = json.getJSONArray("GetCitiesResult").toList()
.stream()
.map(o -> (String) o)
.collect(Collectors.toList());
list3.forEach(System.out::println);
And printed:
1-Vizag
2-Hyderbad
3-Pune
4-Chennai
9-123
11-Rohatash
12-gopi
13-Rohatash
14-Rohatash
10-123
below is code:
private void parse(String response) {
try {
List<String> stringList = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("GetCitiesResult");
for (int i=0; i <jsonArray.length(); i++){
stringList.add(jsonArray.getString(i));
}
Log.d ("asd", "--------"+ stringList);
} catch (Exception e) {
e.printStackTrace();
}
}
Hope it will help.
Output is when print list :
--------[1-Vizag, 2-Hyderbad, 3-Pune, 4-Chennai, 9-123, 11-Rohatash, 12-gopi, 13-Rohatash, 14-Rohatash, 10-123]
Ok you must know first something about JSON
Json object is be {// some attribute}
Json Array is be [// some attribute]
Now You have
{"GetCitiesResult":["1-Vizag","2-Hyderbad",
"3-Pune","4-Chennai","9-123","11-Rohatash",
"12-gopi","13-Rohatash","14-Rohatash","10-123"]}
That`s Means you have JSON array is GetCitiesResult
which have array of String
Now Try this
JSONObject obj = new JSONObject(data);
JSONArray loadeddata = new JSONArray(obj.getString("GetCitiesResult"));
for (int i = 0; i <DoctorData.length(); i++) {// what to do here}
where data is your String
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.
This is my JSON data.
{"JSONDATA":[{"key":0,"value":"--Any--"},{"key":61,"value":"Accounting"},{"key":81,"value":"Aerospace & Defense"},{"key":72,"value":"Automotive"},{"key":83,"value":"Banking"},{"key":84,"value":"Biotech"},{"key":85,"value":"Construction"},{"key":86,"value":"Customer Service"},{"key":87,"value":"Education"},{"key":82,"value":"Energy"},{"key":70,"value":"Finance"},{"key":193,"value":"Government"},{"key":194,"value":"Healthcare"},{"key":71,"value":"Insurance"},{"key":73,"value":"Legal"},{"key":62,"value":"Management"},{"key":63,"value":"Manufacturing"},{"key":64,"value":"Marketing\/Advertising"},{"key":77,"value":"Media - Journalism"},{"key":74,"value":"Pharmaceutical"},{"key":75,"value":"Real Estate"},{"key":76,"value":"Research"},{"key":65,"value":"Restaurant"},{"key":66,"value":"Retail"},{"key":67,"value":"Sales"},{"key":78,"value":"Science"},{"key":68,"value":"Telecommunications"},{"key":79,"value":"Training"},{"key":69,"value":"Transportation"},{"key":80,"value":"Utilities"}]}
I want to decode it on my Android App, This is the code i have used., But i don't get anything on my output. No errors too.
JSONObject jObject= new JSONObject();
JSONArray menuObject = new JSONArray(jObject.getString("JSONDATA"));
String app;
for (int i = 0; i<menuObject.length(); i++) {
{
app=menuObject.getJSONObject(i).getString("value").toString();
a.append(app); // a is my TextView
}
First off, you're not initializing your jObject with anything.
//pass in string
JSONObject jObject= new JSONObject(jsonString);
JSONObjects need something to parse, otherwise (the way you have it now) they initialize with no data, which isn't very helpful.
Secondly, you're using getString when you really want an array:
JSONArray menuObject = jObject.getJSONArray("JSONDATA");
getString is designed to return a piece of string data from a JSON object. "JSONDATA" holds an array, so we need to choose the correct type to retrieve.
Thirdly, you have a redundant toString(), as getString already returns a String:
app=menuObject.getJSONObject(i).getString("value");
Its wrong:
JSONArray menuObject = new JSONArray(jObject.getString("JSONDATA"));
Try:
JSONObject jObject= new JSONObject(yourJSONString);
JSONArray menuObject = jObject.getJSONArray("JSONDATA");
Keep one thing in mind:
Create a JSON Object with JSON String you want to parse and then you can fetch String/JSON Object or JSON Array from the created JSON Object.
Store your json response in a String
String jsonResponse="YOUR JSON RESPONSE STRING";
//Pass the string as below
JSONObject jObject= new JSONObject(jsonResponse);
JSONArray menuObject = jObject.getJSONArray("JSONDATA"));
String app;
for (int i = 0; i<menuObject.length(); i++) {
{
app=menuObject.getJSONObject(i).getString("value").toString();
a.append(app); // a is my TextView
}
Use the appropiate getters and setters in JSONObject and JSONArray, and your "JSONDATA" entry is not a string. Do something like this:
JSONObject jObject = new JSONObject(yourJsonString);
JSONArray menuArray = jObject.getJSONArray("JSONDATA");
for (int i = 0; i < menuArray.length(); i++) {
String app = menuObject.getJSONObject(i).getString("value");
a.append(app); // a is my TextView
}
Use following code for parse your json string.
JSONObject obj = new JSONObject(youtString);
JSONArray array = obj.getJSONArray("JSONDATA");
for (int i = 0; i < array.length(); i++) {
JSONObject c = array.getJSONObject(i);
String key = c.getString("key");
String value = c.getString("value");
a.append(value);
}
Use this:-
String result="[{"key":0,"value":"--Any--"},{"key":61,"value":"Accounting"},{"key":81,"value":"Aerospace & Defense"},{"key":72,"value":"Automotive"},{"key":83,"value":"Banking"},{"key":84,"value":"Biotech"},{"key":85,"value":"Construction"},{"key":86,"value":"Customer Service"},{"key":87,"value":"Education"},{"key":82,"value":"Energy"},{"key":70,"value":"Finance"},{"key":193,"value":"Government"},{"key":194,"value":"Healthcare"},{"key":71,"value":"Insurance"},{"key":73,"value":"Legal"},{"key":62,"value":"Management"},{"key":63,"value":"Manufacturing"},{"key":64,"value":"Marketing\/Advertising"},{"key":77,"value":"Media - Journalism"},{"key":74,"value":"Pharmaceutical"},{"key":75,"value":"Real Estate"},{"key":76,"value":"Research"},{"key":65,"value":"Restaurant"},{"key":66,"value":"Retail"},{"key":67,"value":"Sales"},{"key":78,"value":"Science"},{"key":68,"value":"Telecommunications"},{"key":79,"value":"Training"},{"key":69,"value":"Transportation"},{"key":80,"value":"Utilities"}]";
JSONArray menuObject = new JSONArray(result);
String app;
for (int i = 0; i<menuObject.length(); i++) {
{
app=menuObject.getJSONObject(i).getString("value").toString();
a.append(app); // a is my TextView
}