How to put in array the children of the children - java

private static JSONArray getListOfChildPagesAsJSON(Page page) {
JSONArray pagesArray = new JSONArray();
try {
Iterator<Page> childPages = page.listChildren();
while (childPages.hasNext()) {
Page childPage = childPages.next();
JSONObject pageObject = new JSONObject();
pageObject.put(childPage.getTitle(), childPage.getPath());
pagesArray.put(pageObject);
}
} catch (JSONException e) {
LOG.error(e.getMessage(), e);
}
return pagesArray;
}
So that not only the children of the transferred page put into array, but also the children of the children.

This is a classical case for recursion, like reading directoy tree on filesystem. My suggestion is as follows:
First step: Change the scope of variable JSONArray pagesArray = new JSONArray(); from function to class scope.
public MyClass {
private JSONArray pagesArray = new JSONArray();
...
}
Step two: Change return value to void and the modifier of your function by removing static.
private void getListOfChildPagesAsJSON(Page page) { }
Step three add the missing recusion to your its body.
//JSONArray pagesArray = new JSONArray();
try {
Iterator<Page> childPages = page.listChildren();
while (childPages.hasNext()) {
Page childPage = childPages.next();
JSONObject pageObject = new JSONObject();
pageObject.put(childPage.getTitle(), childPage.getPath());
//Add the created object to your array which is class variable
this.pagesArray.put(pageObject);
//--Check for each single page for child pages again
Iterator<Page> childPagesOfChildpage = childPage.listChildren();
while (childPagesOfChildpage.hasNext()) {
getListOfChildPagesAsJSON(childPagesOfChildpage.next());
}
//--
}
} catch (JSONException e) {
LOG.error(e.getMessage(), e);
}
Note: The check childPage.hasChild() does not work here, because the node jcr:content is a valid child of passed page.

Related

Getting value from json item in java

I have a json file, for example:
{
"A":"-0.4",
"B":"-0.2",
"C":"-0.2",
"D":"X",
"E":"0.2",
"F":"0.2",
"J":"0.3"
}
I want return each element of a list json when I call it via my function.
I did a function to do this:
public JSONObject my_function() {
JSONParser parser = new JSONParser();
List<JSONObject> records = new ArrayList<JSONObject>();
try (FileReader reader = new FileReader("File.json")) {
//Read JSON file
Object obj = parser.parse(reader);
JSONObject docs = (JSONObject) obj;
LOGGER.info("read elements" + docs); // it display all a list of a json file like this: {"A":"-0.4","B":"-0.2","C":"-0.2","D":"X","E":"0.2","F":"0.2","J":"0.3"}
for (int i = 0; i < docs.size(); i++) {
records.add((JSONObject) docs.get(i));
System.out.println((records)); // it return null
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
LOGGER.info("The first element of a list is:" +records.get(0)); // return null
return records.get(0);
How can I change my function to return the value of each element in a json file.
For example, when I call my_function:
my_function.get("A") should display -0.4
Thank you
First you need a Class for mapping
public class Json {
private String a;
private String b;
private String c;
private String d;
private String e;
private String f;
private String j;
//getters and setters
}
Then in your working class
ObjectMapper mapper = new ObjectMapper();
//JSON from file to Object
Json jsn = mapper.readValue(new File("File.json"), Json.class);
then you can use that object in a usual way...
here is the dependency I used
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
Reference
In Java you can use only class`s methods, as I know.
If you want to get your second element by its first, you should in your class create 2 methods like
class Main {
Map<String, String> records = new HashMap<>();
public JSONObject my_function() {
// your realization where you should insert your pairs into Map.
}
public String get(String firstElement){
return map.getValue(firstElement);
}
}
class someOtherClass {
Main main = new Main();
main .my_function();
main .get("A");
}

Split jsonarray data into multiple list using array value

I want to split an ArrayList according to the existing data, Like as
category etc.
I try nested for loop and add them into list.but It's not working.
String url = "http://27.147.169.230/UpSkillService/UpSkillsService.svc/" + "GetCNCCourseDefByorg/" + 1 +"/" +1;
Ion.with(getApplicationContext())
.load("GET",url)
.setBodyParameter("","")
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
Log.d("Result",result);
try {
JSONObject obj =new JSONObject(result);
JSONArray jsonArray = obj.getJSONArray("GetCNCCourseDefByorgResult");
//Arrays.sort(new JSONArray[]{jsonArray});
if(obj.isNull("GetCNCCourseDefByorgResult"))
{
Toast.makeText(getApplicationContext(),"No Course Found",Toast.LENGTH_SHORT).show();
}
else if (!obj.equals(null)) {
String cata="";
Log.d("Resul3", jsonArray.toString());
for (int i = 0; i < jsonArray.length(); i++) {
final CourseCatagory catagoryModel = new CourseCatagory();
JSONObject course = jsonArray.getJSONObject(i);
CourseList courselist = new CourseList();
if(cata!=course.getString("CategoryName"))
{
Log.d("Catagory",cata);
catagoryModel.setCategoryName(course.getString("CategoryName"));
arrayListcatagory.add(catagoryModel);
for (int j=0;j<jsonArray.length();j++)
{
JSONObject cat1 = jsonArray.getJSONObject(j);
cata=cat1.getString("CategoryName");
Log.d("cat",cata);
if(cat1.getString("CategoryName")==course.getString("CategoryName"))
{
courselist.setCourseName(cat1.getString("CourseName"));
courselist.setCourseCode(cat1.getString("CourseCode"));
courselist.setWishFlag(cat1.getInt("WishFlag"));
Log.d("Course",cat1.getString("CourseName"));
arrayListcourse.add(courselist);
}
else {
}
}
}
catagoryModel.setCourseList(arrayListcourse);
}
adapter.notifyDataSetChanged();
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
});
}
`
I want as catagory, under catagory course shown which match catagory name.
Accounting>Introduction Accounting,Advance accounting
Finance>Introduction Finance
You can Use HashMap<String,ArrayList<CategoryDetails>> to resolve your Problem.
First Create CategoryDetails POJO class
class CategoryDetails {
private courseName;
private courseCode;
private wishFlag;
//make setter and getter methods for above fields.
}
Then use category Name as key in HashMap to differentiate as mentioned in first line of my answer.
Map<String,ArrayList<CategoryDetails>> listCategory = new HashMap<String,ArrayList<CategoryDetails>>;

Accessing the JSON data from the method in android

Example of class that will hold the properties in JSONObject and then return the object properties
class OperatorProperties {
JSONObject TigoProperties()
{
JSONObject property = new JSONObject();
try {
property.put("color", "#223f99");
property.put("logo", R.drawable.tigo);
}catch (JSONException e){
e.printStackTrace();
}
return property;
}
}
Problems, I don't know how to get the properties details from the JSONObejct
JSONObject d = OperatorProperties.TigoProperties();
operatorLogo.setImageResource(d);
Any help please because am just want every property should come from the JSONObject

Pass a String[] as parameter not working

I have this class now working fine, but I've been struggling with it many hours to end of changing in it on a different logic from my first approach.
public class MyClass {
public static MyClass tablas;
public static String[] GROUPS;
public static String[] ESTATUS
public static String[] CLIENTS;
public void init(){
this.tablas = new MyClass();
this.setGroups();
CLIENTS=this.setAny("/servlets/CLIENTS","page_rows","nombre");
ESTADO_PEDIDO= new String[]{"str1","str2","str3","str4","str5"};
}
private String[] setAny(String sevlet,String bigNode,String smallNode){
String[] ret=null;
HashMap<String, String> parameters = new HashMap<String, String>();
parameters.put("operation", "4");
parameters.put("avance", "0");
InputStream is = Connection.con.processRequest("GET", sevlet, parameters);
Document dom = null;
try {
dom = UtilesDom.parseXML(is);
NodeList lines = dom.getElementsByTagName(bigNode);
Element el = (Element)lines.item(0);
NodeList nlist = el.getElementsByTagName(smallNode);
ret = new String[nlist.getLength()];
for (int i = 0; i < nlist.getLength(); i++) {
ret[i] = nlist.item(i).getTextContent();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return ret;
}
private void setGroups(){
HashMap<String, String> parameters = new HashMap<String, String>();
parameters.put("operation", "4");
parameters.put("avance", "0");
InputStream is = Connection.con.processRequest("GET", "/servlets/GROUPS_CLIENTS", parameters);
Document dom = null;
try {
dom = UtilesDom.parseXML(is);
NodeList lines = dom.getElementsByTagName("lines");
Element el = (Element)lines.item(0);
NodeList nlist = el.getElementsByTagName("GROUP");
GROUPS = new String[nlist.getLength()];
for (int i = 0; i < nlist.getLength(); i++) {
GROUPS[i] = nlist.item(i).getTextContent();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
As you can see there is two similar methods setGroups and setAny these are used to fill the Strings[] on top.setGroups was my original method but when I needed different Strings[] thought that a "less hard-coded" and most flexible method would be nice, so I tried this:
private void setAny(String sevlet,String bigNode,String smallNode,String[] which){
HashMap<String, String> parameters = new HashMap<String, String>();
parameters.put("operation", "4");
parameters.put("avance", "0");
InputStream is = Connection.con.processRequest("GET", sevlet, parameters);
Document dom = null;
try {
dom = UtilesDom.parseXML(is);
NodeList lines = dom.getElementsByTagName(bigNode);
Element el = (Element)lines.item(0);
NodeList nlist = el.getElementsByTagName(smallNode);
which = new String[nlist.getLength()];
for (int i = 0; i < nlist.getLength(); i++) {
which[i] = nlist.item(i).getTextContent();
System.out.println(which[i]);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
Using the call like:
this.setAny("/principal/Clientes","page_rows","nombre",CLIENTS);
also
this.setAny("/principal/Clientes","page_rows","nombre",this.CLIENTS);
and
this.setAny("/principal/Clientes","page_rows","nombre",this.tablas.CLIENTS);
The problem with it is that the String[] passed as parameter (aka CLIENTS) just stay null , and yes at the en of the for loop its populated properly and the console shows what it supposed to.So the question is:
Why String[] CLIENTS cant be populated when passed as a parameter,and just stay as null?
PD: As you may notice English is not my language so please suggest any grammar/redaction/spelling... corrections.
Okay so I'm gonna pretend your parameter is a String[] and not a String here.
Your problem is that once you create a new array with the new operator, your reference changes to that new array. So the old one isn't affected.
So yes, you create a new array and fill it properly, but sadly it won't be CLIENTS. If you do it like in your first example and return the String Array to save it, that will work.
Another option would be to create a static HashMap of String Arrays instead of just three different static String Arrays. Then you can pass the key to the method and just replace the Array at the given key. That way you don't need to work with a return value.
It is null at runtime and the compile dont know about that. It strictly checks the type at compile time it self.
setAny(String sevlet,String bigNode,String smallNode)
That last parameter is a String and you are trying to pass an Array. Probably you need to change the signature as
setAny(String sevlet,String bigNode,String smallNode[])
So that it receives an array.

How can i use a constructor of a generic class

i got multiple classes which do basicly the same. I pass a JSONObject in the constructor an it sets some variabes.
Now i got some other classes which create those first classes and add them to a ArrayList. Now i want to merge the second classes to one using generics.
This is what I want to do:
public class Data<T> {
public ArrayList<T> data;
public Data(String response1) {
data = new ArrayList<T>();
JSONArray ja;
try {
ja = new JSONArray(response1);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
data.add(new T(jo));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
but it doesnt let me create an Instance of T with
new T(jo);
Would be nice if someone can help me
There is a standard trick for this situations: pass Class<T> along with the String data into the call, and add a setter for the JSONObject. This would let you call a parameterless constructor, like this:
interface WithJson {
void setJson(JSONObject jo);
}
public class Data<T extends WithJson> {
public Data(String response1, Class<T> type) {
data = new ArrayList<T>();
JSONArray ja;
try {
ja = new JSONArray(response1);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
T obj = type.newInstance();
object.setJson(jo);
data.add(obj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The Class<T> has been modified in Java 5 to let you use it as a factory for the instances of that class. The call of type.newInstance is checked statically for type safety. The addition of the interface WithJson lets you call setJson method on the instances of T in a way that the compiler can check statically.
When you construct Data<T>, you need to pass the class being created, like this:
Data<MyContent> d = new Data(jsonString, MyContent.class);
Use a generic factory interface.
public interface Factory<T>
{
public T createFromJSONObject( JSONObject jo );
}
And now a modified constructor:
public Data(
String response1,
Factory<T> factory
) {
data = new ArrayList<T>();
JSONArray ja;
try {
ja = new JSONArray(response1);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
data.add( factory.createFromJSONObject( jo ) );
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Categories