I written the below code
List<UserDetails> getUserList(String Json){
try {
JSONObject jsonObject = new JSONObject(Json);
int myname = jsonObject.getInt("itemsPerPage");
System.out.println(myname);
JSONArray jsonarray = (JSONArray) jsonObject.get("list");
System.out.println(jsonarray.length());
if(null != jsonarray && jsonarray.length() == 25){
RestClient restClient = new RestClient();
URL= someurl;
checkValue="USERDETAILS";
startIndex += 25;
String jsonResult = restClient.postJiveUsersData(URL,restUserName,restPassword);
if(null != jsonResult) {
getUserList(jsonResult);
}
}
System.out.println("User List size::" +userDetailsList.size());
return userDetailsList;
After executing the above the "User List size" is printing more than once. May I know reason and is there any way to avoid tomultiple time to print it.
Thanking for helping in advance.
Regards
Narasimha Reddy P
It is printing more than once because your getUserList method is calling itself, so System.out.println("User List size::" +userDetailsList.size()); is executed multiple times.
Related
My program is to get a list of Java objects from the "result" string derived from the AsyncTask. In order to do so, I need to use JsonParser to get an JsonArray. In case the "result" string is [], the JsonArray is also []. How can I detect if there is any item in this Json array. I've tried all of suggestions, even detected at the "result" string, nothing is working for me, could you please help? My JsonArray: []
try{
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(orderList).getAsJsonArray();
System.out.println("Inside fromJasonToJava, array: " + array); //This prints out array: []
lst = new ArrayList<Order>();
if(array.get(0)!= null) { //It goes wrong here, I need a working "if" condition
//Value is not null
for (final JsonElement json : array) {
JSONObject jsonObject = new JSONObject(String.valueOf(json));
System.out.println("Inside fromJasonToJava, jsonObject:" + jsonObject);
}
}
}catch(Exception e){
throw new Exception("Convert json to java error [fromJasonToJava()]", e);
}
Inside your if check for size instead, if you are using org.json.simple.JSONArray
if(array.size() != 0)
or if you using org.json.JSONArray
if(array.length() != 0)
You may use if(array.length() > 0)
You no need to use the if condition as java's for-each is smart enough to handle this.
If the array doesn't have any vale or it's empty then it will not get executed at all.
So use this code:
for (final JsonElement json : array) { // it will not get executed at all if array is empty
JSONObject jsonObject = new JSONObject(String.valueOf(json));
System.out.println("Inside fromJasonToJava, jsonObject:" + jsonObject);
Instead of
if(array.get(0)!= null) { //It goes wrong here, I need a working "if" condition
//Value is not null
for (final JsonElement json : array) {
JSONObject jsonObject = new JSONObject(String.valueOf(json));
System.out.println("Inside fromJasonToJava, jsonObject:" + jsonObject);
}
I have to read a sample pom file and write all technology and version in to json file, Im able to get the output in this format:
["{ name:junit ,Version:4.12}","{ name:spring-batch-test ,Version:3.0}","{ name:spring-boot-starter }","{ name:slf4j-api }"]
However I want to get output in this format:
[{ "name":"junit" ,"Version":"4.12"},{" name":"spring-batch-test" ,"Version":"3.0"},{"name":"spring-boot-starter" }]
My code :
Map<String, String> dependencies = Maps.newHashMap();
dependencies = populateProjectDepedencies(dependencies, pomFile);
In populateProjectDependencies
for (Dependency dependency : dependencyList) {
String version = "0.0";
if (dependency.getVersion() != null &&
dependency.getVersion().startsWith("${"))
{
version = (String) properties.get(dependency.getVersion()
.substring(2, dependency.getVersion().length() - 1));
} else {
version = dependency.getVersion();
}
if (version != null) {
String a1[]=version.split("\\.");
int i=a1.length;
if(i>=2)
{
version=a1[0]+"."+a1[1];
}
dependencies.put("{name:"+dependency.getArtifactId(),",
Version:"+version+"}" );
JSONArray jsonArray = prepareJsonObject(dependencies);
genarateTechnologyRadarJson(jsonArray);
writer.write(jsonArray.toJSONString());
As I understand from your question, you are holding json as String array but you want to hold data as JSONObject array. So,
JSONArray ja = new JSONArray();
for (Dependency dependency : dependencyList) {
.....
JSONObject obj=new JSONObject();
obj.put("name",dependency.getArtifactId());
obj.put("Version",version);
ja.put(obj);
//remove dependencies.put,JSONArray. and genarateTechnologyRadarJson(jsonArray);
}
writer.write(ja.toString());
UPDATE
This should be your complete code
JSONArray jsonArray = new JSONArray();
for (Dependency dependency: dependencyList) {
String version = "0.0";
if (dependency.getVersion() != null &&
dependency.getVersion().startsWith("${")) {
version = (String) properties.get(dependency.getVersion()
.substring(2, dependency.getVersion().length() - 1));
} else {
version = dependency.getVersion();
}
if (version != null) {
String a1[] = version.split("\\.");
int i = a1.length;
if (i >= 2) {
version = a1[0] + "." + a1[1];
}
}
JSONObject obj=new JSONObject();
obj.put("name",dependency.getArtifactId());
obj.put("Version",version);
jsonArray.put(obj);
}
writer.write(jsonArray.toJSONString());
Because, you are adding the value as a String
"{ name:"+dependency.getArtifactId(),"
Even, I'm not sure why are you manually constructing the JSON instead just pass the Map object to JSONObject.
JSONObject obj=new JSONObject(yourmap);
My JSON data look like this.
{"Users":[
{"Username":"Admin1", "Password":"123"},
{"Username":"Admin2", "Password":"456"},
{"Username":"Admin3", "Password":"789"}
]}
I am trying to extract out all the list of Username and Password.
JSONParser parser=new JSONParser();
Object obj = parser.parse(new FileReader("./Database/Users.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray userArray = (JSONArray) jsonObject.get("Users");
How do I then iterate through this JSONArray to achieve what I wanted?
Sorry if I wasn't clear. I was using org.json.simple, not org.json. And the JSONArray does not have the int length() method.
What I did was
Iterator<JSONObject> iterator = userArray.iterator();
while (iterator.hasNext()) {
JSONObject factObj = (JSONObject) iterator.next();
String userName = (String) factObj.get("Username");
String passWord = (String) factObj.get("Password");
}
Read the javadoc ;)
If you are using org.json.JSONArray, you can loop using int length() to know the array's length and Object get(index) or JSONObject getJSONObject(index) to get an item of the array.
You can iterate with for loop
for (int i = 0; i < userArray.length(); ++i) {
JSONObject user = recs.getJSONObject(i);
...
}
you can probably do something like the following
for(int i = 0; i < userArray.length; i++) {
JSONObject user = userArray.getJSONObject(i);
String username = user.getString("Username");
String password = user.getString("Password");
//etc
}
I am trying to populate multiple selectbox dynamically using $.ajax() method....
Here is my html code......
<select id="imageSize" name="ImageSizeId"></select>
<select id="circulation" name="circulationId"></select>
Here is my servlet code.....
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/json;charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
JSONObject usesfactors = new JSONObject();
JSONArray jArraysize = new JSONArray();
JSONArray jArraycirculation = new JSONArray();
Statement stmtsize,stmtcirculation;
ResultSet rssize,rscirculation;
int category_id = Integer.parseInt(request.getParameter("CategoryId"));
int format_id = Integer.parseInt(request.getParameter("FormatId"));
String size,display,des;
int sizeid;
try {
if(category_id == 2 && format_id == 201){
// Get image size factors
String sql1="SELECT SizeId,Size FROM Size WHERE Category_id = "+category_id+" AND Format_id = "+format_id+" ";
PreparedStatement ps1 = conn.prepareStatement(sql1);
rssize = ps1.executeQuery() ;
if( rssize!=null){
System.out.println("Not Null");// its printing even if resultset rssize has no records.......why?
while(rssize.next())
{
System.out.println("inside resultset");
JSONObject jobj = new JSONObject();
sizeid = rssize.getInt("SizeId");
size=rssize.getString("Size");
System.out.println(size);
jobj.put("SizeId", sizeid);
jobj.put("Size", size);
jArraysize.add(jobj);
}
usesfactors.put("Size", jArraysize);
rssize.close();
}
else{
System.out.println("Does not have Size factors");
}
// Get image circulation factors
String sql2="SELECT circulationId,circulation FROM Circulation WHERE Category_id = "+category_id+" AND Format_id = "+format_id+" ";
PreparedStatement ps2 = conn.prepareStatement(sql2);
rscirculation = ps2.executeQuery() ;
if(rscirculation!=null){
while(rscirculation.next())
{
JSONObject jobj = new JSONObject();
display = rscirculation.getString("DisplayName");
des=rscirculation.getString("Description");
jobj.put("DisplayName", display);
jobj.put("Description", des);
jArraycirculation.add(jobj);
}
usesfactors.put("Circulation", jArraycirculation);
rscirculation.close();
}
else{
System.out.println("Does not have Circulation factors");
}
out.println(usesfactors);
}
i am getting empty json result....?Whts wrong?
{"Size":[],"Circulation":[]}
i don't want to execute this stmt "usesfactors.put("Size", jArraysize);" if resultset rssize is null but this stmt is executing even if result set rssize has no records....
In short i want to put json array(jArraysize) in json object (usesfactors) if and only if result set rssize has records.
In response to the question in the code about why it's getting into the rssize!=null block, see the javadoc on executeQuery. It explicitly states that it never returns null, so the null check always passes. This means that an empty result set will skip the loop in that section, but still hit the line
usesfactors.put("Size", jArraysize);
This should be rewritten to actually avoid the insert on an empty return set. A similar change should be made to correct the circulation section, which also does an ineffective null check.
while(rssize.next())
{
System.out.println("inside resultset");
JSONObject jobj = new JSONObject();
sizeid = rssize.getInt("SizeId");
size=rssize.getString("Size");
System.out.println(size);
jobj.put("SizeId", sizeid);
jobj.put("Size", size);
jArraysize.add(jobj);
}
if (jArraysize.length > 0)
{
usesfactors.put("Size", jArraysize);
}
else
{
System.out.println("Does not have Size factors");
}
rssize.close();
The problem in your code might be your sql queries which are not returning any values.because i have done in my IDE in the same way you have done,only difference is that instead of getting values from database i have kept manually by iterating for loop.below is the code...
JSONObject usesfactors = new JSONObject();
JSONArray jArraysize = new JSONArray();
JSONArray jArraycirculation = new JSONArray();
for(int i=0;i<3;i++)
{
JSONObject jobj = new JSONObject();
jobj.put("SizeId", "1");
jobj.put("Size", "2");
jArraysize.put(jobj);
}
usesfactors.put("Size", jArraysize);
for(int i=0;i<3;i++)
{
JSONObject jobj = new JSONObject();
jobj.put("DisplayName", "3");
jobj.put("Description", "4");
jArraycirculation.put(jobj);
}
usesfactors.put("Circulation", jArraycirculation);
System.out.println(usesfactors);
I have written java code for generating json of my searched data from file.But its not generating exact JsonArray. Its like
[{"item":"1617"},{"item":"1617"}]
instead of
[{"item":"747"},{"item":"1617"}].
Here 1617 is last item which is fetched from file.
JSONArray ja = new JSONArray();
JSONObject jo = new JSONObject();
while (products.readRecord())
{
String productID = products.get("user");
int j = Integer.parseInt(productID);
if(j == userId) {
itemid = products.get("item");
jo.put("item",itemid);
ja.add(jo);
}
}
out.println(ja);
products.close();
you are actually creating one jSONobject object to handle two objects, shouldn't you need to create JSONObjects in the while loop? something like this, so every iteration in while loop will create a new JSONObject and add it to JSONArray
JSONArray ja = new JSONArray();
while (products.readRecord())
{
String productID = products.get("user");
int j = Integer.parseInt(productID, 10);
if(j == userId)
{
JSONObject jo = new JSONObject();
itemid = products.get("item");
jo.put("item", itemid);
ja.add(jo);
}
}
out.println(ja);
products.close();
Extra:
i am not sure how java does conversion for string to integer, but i think you should always specify radix when using parseInt so the strings like '09' will not be treated as octal value and converted to wrong value (atleast this is true in javascript :))
Integer.parseInt(productID, 10);
You must re-instantiate your JSonObject inside the loop because when you modify it you modify the underlying object which is referenced several times by your array. Move your JSONObject jo = new JSONObject(); inside the loop and it should work fine.
Place JSONObject jo = new JSONObject(); inside the loop:
while (products.readRecord())
{
JSONObject jo = new JSONObject();
String productID = products.get("user");
int j = Integer.parseInt(productID);
// etc
}