String json = " {
id : '100000', 
text : '文本100000', 
children : [
{
id : '110000', 
text : '文本110000', 
children : [
{
id : '113000', 
text : '文本113000', 
leaf : true
},
{
id : '111000', 
text : '文本111000', 
leaf : true
},
{
id : '112000', 
text : '文本112000', 
children : [
{
id : '112200', 
text : '文本112200', 
leaf : true
},
{
id : '112100', 
text : '文本112100', 
leaf : true
}
]
}
]
}
]
}";如何解析json,并查找当id='112200'时,输出text值 ,并跳出执行

解决方案 »

  1.   

    用jsonObject 和jsonArray 就行了 直接把你的字符串丢进去就OK了然后解析对象就行
      

  2.   

    关键是这个JSON树结构是无限级的,怎么循环方法我这样只能取出一层来<java>
               try {
                JSONObject jsonObject = new JSONObject(json);          
                JSONArray jsonArray = jsonObject.getJSONArray("id");
               
                for (int i = 0; i < jsonArray.length(); i++) {
                 System.out.println("item " + i + " :" + jsonArray.getString(i));
                      try{
                         JSONObject jsonObject333 = new JSONObject(jsonArray.getString(i));
                        String aaaa = jsonObject333.getString("id");
                        System.out.println("----------"+aaaa);
                        if(aaaa.equals("112200")){
                         System.out.println("-dfdfdfdfdfd---"+aaaa);
                        }
                      }catch(Exception e){
                      }
                }
               } catch (JSONException e) {
                e.printStackTrace();
               }</java>
      

  3.   


               try {
                JSONObject jsonObject = new JSONObject(json);
                JSONArray jsonArray = jsonObject.getJSONArray("id");//此处是不是需要把JSON字符串改下才可以,不然也不是数组呀
               
                for (int i = 0; i < jsonArray.length(); i++) {
                 System.out.println("item " + i + " :" + jsonArray.getString(i));
                      try{
                         JSONObject jsonObject333 = new JSONObject(jsonArray.getString(i));
                        String aaaa = jsonObject333.getString("id");
                        System.out.println("----------"+aaaa);
                        if(aaaa.equals("112200")){
                         System.out.println("-dfdfdfdfdfd---"+aaaa);
                        }
                      }catch(Exception e){
                      }
                }
               } catch (JSONException e) {
                e.printStackTrace();
               }
      

  4.   


    package com.zf.test;import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class Resolve { public List<Node>  resolve(String json){
    Stack<Integer> stack = new Stack<Integer>(json.length());   //保存 { 符号的索引
    //key --父节点在栈中{符号的索引       value--> children  
    Map<Integer , List<Node>> childrenMap = new HashMap<Integer , List<Node>>();
    List<Node>  nodes = new ArrayList<Node>(); //保存解析出来的Node集合  
    for (int i = 0; i < json.length(); i++) {
    char c = json.charAt(i);  
    switch(c){
    case '{': //入栈
    stack.push(i);
    break;
    case '}':
    int lastOpra = stack.pop(); //将上一个{符号的索引  出栈
    String nodeStr = json.substring(lastOpra + 1, i);
    Node node = strToNode(nodeStr);
    node.children = childrenMap.remove(lastOpra); //从map中找到该元素的children,并从map中移除
    nodes.add(node); if(!stack.isEmpty()){ //如果栈不为空,表示该元素有父节点,就将该元素存入map
    List<Node> children = childrenMap.get(stack.peek());
    if(children == null)
    children = new ArrayList<Node>();
    children.add(node);
    childrenMap.put(stack.peek(), children); 
    }
    break;
    }
    }
    return nodes;
    }
    //将字符串转换为Node对象
    public Node strToNode(String str){
    Node node = new Node();
    Matcher mId = Pattern.compile("id\\s*:\\s*'(\\d+)'").matcher(str);
    Matcher mText = Pattern.compile("text\\s*:\\s*'(.*?)'").matcher(str);
    Matcher mLeaf = Pattern.compile("leaf\\s*:\\s*(true|false)").matcher(str);
    if(mId.find())
    node.id = mId.group(1);
    if(mText.find())
    node.text = mText.group(1); 
    if(mLeaf.find())
    node.leaf = mLeaf.group(1).equals("true")? true:false;  
    return node;
    } public static void main(String[] args) {
    Resolve r = new Resolve();
    String json = "{id : '100000',text : '文本100000',children : [{id : '110000',text : '文本110000',children : [{id : '113000',text : '文本113000',leaf : true},{id : '111000', text : '文本111000', leaf : true},{id : '112000',text : '文本112000',children : [{id : '112200',text : '文本112200',leaf : true},{id : '112100', text : '文本112100', leaf : true}]}]}]}";
    List<Node> nodes = r.resolve(json);  //解析得到所有的Node
    for (Node node : nodes) {
    if(node.id.equals("112200")){  //查找id = 112200的node
    System.out.println("id :" + node.id);
    System.out.println("text :" + node.text);
    System.out.println("leaf :" + node.leaf);
    System.out.print("children : " );
    if(node.children != null)
    for (Node child : node.children) { //该节点的所有children
    System.out.print(child.id + "  ");
    }
    }
    }
    }}//实体类
    class Node{ String id ;
    String text ;
    boolean leaf ;
    List<Node> children = new ArrayList<Node>(); @Override
    public String toString() {
    StringBuffer str = new StringBuffer("id: " + id + " text: " + text + " leaf: " + leaf);
    if(children != null){
    str.append(" children : ");
    for (Node node : children) {
    str.append(node.id + " ");
    }
    }
    return str.toString() ;
    }
    }//工具类   栈
    class Stack<E>{ private Object array[] ;
    private int maxLength ;
    private int size ;  public Stack(int maxLength){
    this.maxLength = maxLength;
    array = new Object[maxLength];
    } public void push(E e){ //入栈
    if(isFull()) throw new RuntimeException("array is full!");
    array[size++] = e;
    } public E pop(){ //出栈  
    if(isEmpty()) throw new RuntimeException("array is empty!");
    return (E)array[size-- - 1]; 
    } public E peek(){ //查看栈顶元素
    return (E)array[size -1];
    } public boolean isEmpty(){
    return size == 0 ;
    } public boolean isFull(){
    return size == maxLength;
    }}
      

  5.   

    在calss Node 处报错提示:The type node is already defined
      

  6.   

    你的包中已经有Node类了, 你把Node类改个类名就行了。
      

  7.   

            Matcher mId = Pattern.compile("id\\s*:\\s*'(\\d+)'").matcher(str);
            Matcher mText = Pattern.compile("text\\s*:\\s*'(.*?)'").matcher(str);
            Matcher mLeaf = Pattern.compile("leaf\\s*:\\s*(true|false)").matcher(str);这三句正则是什么意思
      

  8.   

    mId  匹配 id :后面 '' 符号里面的数字
    mText 匹配 text:后面''符号里面的字符串
    mLeaf 匹配  leaf: 后面的字符串,并且该字符串为 true 和 false 里面的一个
      

  9.   

    node.id = mId.group(1);
    这里啥意思mId.group(1);
      

  10.   

    用递归做import net.sf.json.JSONArray;
    import net.sf.json.JSONObject;public class TestJson {
    public static void main(String[] args){
    String json = "{                                               "
    +"         id : '100000',                                        " 
    +"         text : '文本100000',                                  "
    +"         children : [                                          "
    +"                 {                                             "
    +"                 id : '110000',                                "
    +"                 text : '文本110000',                          "
    +"                 children : [                                  "
    +"                         {                                     "
    +"                         id : '113000',                        "
    +"                         text : '文本113000',                  "
    +"                         leaf : true                           "
    +"                         },                                    "
    +"                         {                                     "
    +"                         id : '111000',                        "
    +"                         text : '文本111000',                  "
    +"                         leaf : true                           "
    +"                         },                                    "
    +"                         {                                     "
    +"                         id : '112000',                        "
    +"                         text : '文本112000',                  "
    +"                         children : [                          "
    +"                                 {                             "
    +"                                 id : '112200',                "
    +"                                 text : '文本112200',          "
    +"                                 leaf : true                   "
    +"                                 },                            "
    +"                                 {                             "
    +"                                 id : '112100',                "
    +"                                 text : '文本112100',          "
    +"                                 leaf : true                   "
    +"                                 }                             "
    +"                         ]                                     "
    +"                         }                                     "
    +"                 ]                                             "
    +"                 }                                             "
    +"         ]                                                     "
    +"     }";     

    JSONObject jsonObject = JSONObject.fromObject(json);

    System.out.println(method(jsonObject,"112200"));
    }

    public static String method(JSONObject jsonObject,String idValue){
    String id= (String)jsonObject.get("id");
    String text= (String)jsonObject.get("text");

    if(id.equals(idValue)){
    return text;
    }

    Boolean leaf= (Boolean)jsonObject.get("leaf");
    if(leaf==null||!leaf.booleanValue()){
    JSONArray childrens=(JSONArray)jsonObject.get("children");
    for(int i=0;i<childrens.size();i++){
    String resulttext=method((JSONObject)childrens.get(i),idValue);
    if(resulttext!=null) return resulttext;
    }

    }
    return null;
    }}
      

  11.   

    import org.richfaces.json.JSONArray;
    import org.richfaces.json.JSONException;
    import org.richfaces.json.JSONObject;
    public class Test extends Thread{
    private JSONObject _jsonObject;

    public Test(JSONObject jsonObject){
    this._jsonObject=jsonObject;
    }


    @Override
    public void run() {
    try {

    if (_jsonObject.get("id").equals("112200")) {
    System.out.println(_jsonObject.get("text"));
    }else {
    JSONArray jsonArray=getSubObject();
    for (int i = 0; i < jsonArray.length(); i++) {
    new Test(jsonArray.getJSONObject(i)).start();
    }
    }
    } catch (Exception e) {
    //never 
    }
    }

    private JSONArray getSubObject(){
    try {
    return _jsonObject.getJSONArray("children");
    } catch (Exception e) {
    }
    return new JSONArray();
    }

    public static void main(String[] args) throws JSONException {
    final String jsonStr="{ id : '100000', text : '文本100000', children : [  {id : '110000',  text : '文本110000',children : ["+
     " { id : '113000',  text : '文本113000',leaf : true },{id : '111000',  text : '文本111000', leaf : true},{ id : '112000',  text : '文本112000', "+
     "children : [{  id : '112200',    text : '文本112200',  leaf : true},  {id : '112100',   text : '文本112100',   leaf : true } ]  }] } ] }";

    new Test(new JSONObject(jsonStr)).start();
    }
    }
      

  12.   

    GSON也不错啊,比较面向对象……
      

  13.   

    org.richfaces.json.JSONArray
    是那个包
      

  14.   

    你随便下哪个JSON包都差不多的,换汤不换药。。
      

  15.   

    你的json格式错误,key应该用双引号""括起来