2016-02-27 45 views
1

我正在读java中的一组节点。每个节点都是一个国家的。每个节点都有属性“国家”,像美国这样的国家也有“国家”属性节点。这种“状态”是万事的一部分,因此每个项目都有一个状态,这是一起在一个节点是这样的:AEM:从一个多字段值的java节点读取一个值

country = "US" 
, states = [{"statename":"District of Columbia"}, {"statename":"Rhode Island"},{"statename":"South Dakota"}] 

我想填充他们通过一个servlet调用这样的页面JSON :

http://localhost:4502/bin/utilservlet.json

{ 
    country: "India" 
    { 
     statename:"Delhi", 
     statename:"Punjab", 
     statename:"Haryana" 
    } 
} 

{ 
    country: "Turkey" 
} 

下面是我的代码:

while (nodeItr.hasNext()) { 
        Node cNode = nodeItr.nextNode(); 
        if (cNode.hasProperty("country")) { 
         JSONObject jsonData = new JSONObject(); 
         jsonData.put("country", childNode.getProperty("countryname").getValue().getString()); 
         jsonArray.put(jsonData); 
         if (cNode.hasProperty("states")) { 
// This should display array of all states as an when it is encountered. 
LOG.info(childNode.getProperty("states").getValue().getString()); 

以下情况发生: 1.除了州属性出口的第一个国家外,我获得了所有国家/地区列表。 2.没有其他国家在那里显示状态列表。

我在做什么错?

+0

为节点自定义类,如果有,请提供它的代码。 – Anil

+0

节点是javax.jcr.Node类; – Ajax

+0

所以我试图理解,你是否能够通过节点(我的意思是所有国家和它们的相应状态)读取所有数据,并且无法将其写入JSON格式。或者你甚至无法读取它? – Anil

回答

0

尝试以下操作:

if (cNode.hasProperty("states")) { 
    Property statesProperty = cNode.getProperty("states"); 
    if (statesProperty.isMultiple()) { 
     Value[] statesValues = states.getValues(); 
     for (Value stateValue : stateValues) { 
      LOG.info(stateValue.getString()); 
     } 
    } 
} 
+0

谢谢,它解决了这个问题。 – Ajax

+0

你也可以请回答这一个:http://stackoverflow.com/questions/35685126/aem-getting-states-matching-country-from-another-node – Ajax

+0

我想提醒人们,使用org.apache.sling .api.resource.Resource,org.apache.sling.api.resource.ValueMap接口而不是低级别的javax.jcr.Node,javax.jcr.Property。它们更易于使用,不会抛出异常,并导致更简单,更易维护的代码。 –