2012-11-07 7 views
2

저는 Java에서 JSON 조작을 처음 사용하고 클래스 속성에 액세스하고 입력해야하는 여러 레이어가있는 JSON 배열 형태의 문자열을가집니다. 내가이 n 개의 Object의 배열, 각 포함 "attributeOne, attributeTwo입니다 알고,이 문자열을 구문 분석하는 방법,자바에서 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에 있다고 가정하자 : 예를 들어, 여기 내 JSON 객체의 , ..., 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 감사를 사전에 도움을!

+0

왜 'GSON'을 사용하지 않습니까? 그것의 간단하고 빠른. 모든 클래스를 String으로 변환하면됩니다. –

+0

잭슨은 gson보다 빠르며 사용하기 쉽습니다. – digitaljoel

답변

1

: http://code.google.com/p/google-gson/

문서는 예를 객체가 (instanceof를 사용하는 + 나쁜 관행)

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; 
} 

그러나 그 복잡 조금하고 돈 바퀴를 재발 명하고 싶지 않습니다. 따라서 GSON 또는 Jackson을 사용하십시오.

Gson gson = new Gson(); 
String myClassStr = gson.toGson(MyClassInstance); 
.... 
    Myclass yourClass = gson.fromJson(myClassStr, Myclass.class); 
2

잭슨 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 컨텍스트에서는 적절한 주석을 사용하여 엔드 포인트에서이 비 정렬 기능을 가져올 수 있습니다.

+0

페스 나를 이길! – Alex