2

私はJavaでのJSON操作は初めてで、アクセスしてクラス属性に入れる必要があるいくつかのレイヤーを持つJSON配列の形式の文字列があります。たとえば、これが私の 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 というクラスがあるとします。この文字列をどのように解析すればよいでしょうか。これは、それぞれが「attributeOne、attributeTwo、...、attributeFive」を含む n 個のオブジェクトの配列であることを知っていますか?

これが私がこれまでに持っているものです:

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 事前に助けてくれてありがとう!

4

3 に答える 3

2

ジャクソン JSON を試してください:

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

この2つのライナーを次から取得しました:

http://wiki.fasterxml.com/JacksonInFiveMinutes

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

JSON ストロングをオブジェクトに変換する必要があります。Java EE コンテキストでは、適切なアノテーションを使用してエンドポイントでこのアンマーシャリング機能を取得できる場合があります。

于 2012-11-07T21:32:22.317 に答える
1

あなたがやろうとしているやり方は苦痛で複雑です。

GSON のようなライブラリを使用して、面倒な作業を任せることをお勧めします。 http://code.google.com/p/google-gson/

ドキュメントにはオブジェクトの例があります: https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples

于 2012-11-07T21:23:00.660 に答える
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);
于 2012-11-07T21:31:02.247 に答える