JSON数组字符串到Java中的JSONArray对象

时间:2012-11-07 21:14:55

标签: java parsing arrays

我是Java中JSON操作的新手,我有一个JSON数组形式的String,我需要访问几个层并将其放入类属性中。例如,这是我的JSON对象:

{"JsonObject" : [{"attributeOne":"valueOne",
                  "attributeTwo":"valueTwo",
                  "attributeThree":[{"subAttributeOne":"subValueOne",
                                     "subAttributeTwo":"subValueTwo"}],
                  "attributeFour":[{"subAttributeOne":"subValueThree",
                                    "subAttributeTwo":"subValueFour"}],
                  "attributeFive":"valueThree"},
                 {"attributeOne":"valueFour",
                  "attributeTwo":"valueFive",
                  "attributeThree":[{"subAttributeOne":"subValueFive",
                                     "subAttributeTwo":"subValueSix"}],
                  "attributeFour":[{"subAttributeOne":"subValueSeven",
                                    "subAttributeTwo":"subValueEight"}],
                  "attributeFive":"valueSix"}]}

假设我有一个名为MyClass的类具有这些属性,我将如何解析此字符串,知道这是一个n个对象的数组,每个包含“attributeOne,attributeTwo,...,attributeFive”?

这是我到目前为止所拥有的:

public MyClass[] jsonToJava (String jsonObj)
{
    ArrayList<MyClass> myClassArray = new ArrayList<MyClass>();


    //Somehow create a JSONArray from my jsonObj String
    JSONArray jsonArr = new JSONArray(jsonObj); //Don't know if this would be correct

    for(int i=0; i<jsonArr.length; i++){
        MyClass myClassObject = new MyClass();
        myClassObject.setAttributeOne = jsonArr[i].getString("attributeOne");
        // How can I access the subAttributeOne and Two under attributeThree and Four?
        // add all other values to myClassObject
        myClassArray.add(myClassObject);
    }
    return myClassArray;
}

你可能会说,我对编程很新:P提前感谢你的帮助!

3 个答案:

答案 0 :(得分:2)

尝试Jackson JSON:

ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
User user = mapper.readValue(jsonObj, User.class); //method overloaded to take String

抓住了这两个班轮:

http://wiki.fasterxml.com/JacksonInFiveMinutes

http://jackson.codehaus.org/0.9.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html

应将您的JSON强大转换为对象。在Java EE上下文中,您可以使用适当的注释在端点上获取此解组功能。

答案 1 :(得分:1)

你试图这样做的方式是痛苦和参与。

我建议您使用像GSON这样的库,并让它完成繁重的工作。 http://code.google.com/p/google-gson/

文档包含对象示例:https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples

答案 2 :(得分:1)

对于您的示例,您可以使用类似的递归:

    public Object getChild(Object parent, int index) { 

    if (parent instanceof JSONArray) {          

        try {
            Object o =  ( (JSONArray)parent ).get(index);

            if( o instanceof JSONObject ){
                parent =  ((JSONObject) ( o ) ).getMap();                   
                return parent;
            }

            if( o instanceof Double ){
                parent =  (Double) o;                   
                return parent;
            }

            if( o instanceof Integer ){
                parent =  (Integer) o;                  
                return parent;
            }
                            ....


        } catch (JSONException e1) {
            e1.printStackTrace();
        }       
    }



    if (parent instanceof JSONObject) {             
        parent = ( (JSONObject)parent ).getMap();
    }

    if (parent instanceof Map<?, ?>) { 
        Map<?, ?> map = (Map<?, ?>) parent; 
        Iterator<?> it = map.keySet().iterator(); 
        for (int i=0; i<index; i++){
            it.next(); 
        }

        return map.get(it.next()); 
    }
    else if (parent instanceof Collection<?>) { 
        Iterator<?> it = ((Collection<?>) parent).iterator(); 

        for (int i=0; i<index; i++){
            it.next();              
        }
        return it.next(); 
    } 
    //throw new IndexOutOfBoundsException("'" + parent + "'cannot have children!"); 
    return null;
} 

但它有点复杂(+使用instanceof的不良做法)并且你不想重新发明轮子。所以使用GSON或Jackson。

 Gson gson =  new Gson();
 String myClassStr = gson.toGson(MyClassInstance);
 ....
  Myclass yourClass = gson.fromJson(myClassStr, Myclass.class);
相关问题