2013-08-04 3 views
1

구문 분석이 내 JSON 배열입니다 :루프는 파괴되지 않는다 - JSON은 GSON

36 100 "The 3n + 1 problem" 56717 
:

[ 
     [ 36, 
     100, 
     "The 3n + 1 problem", 
     56717, 
     0, 
     1000000000, 
     0, 
     6316, 
     0, 
     0, 
     88834, 
     0, 
     45930, 
     0, 
     46527, 
     5209, 
     200860, 
     3597, 
     149256, 
     3000, 
     1 
     ], 
     [ 
     ........ 
     ], 
     [ 
     ........ 
     ], 
     .....// and almost 5000 arrays like above 
] 

I에 넣었다 배열의 첫 번째 네 개의 값이 필요하고 같은 값의 나머지 부분을 건너 뛰려면

그리고 이것은 내가 지금까지 쓴 코드 :

reader.beginArray(); 
while (reader.hasNext()) { 
    reader.beginArray(); 
    while (reader.hasNext()) { 
     System.out.println(reader.nextInt() + " " + reader.nextInt() 
          + " " + reader.nextString() + " " 
          + reader.nextInt()); 
     for (int i = 0; i < 17; i++) { 
      reader.skipValue(); 
     } 
     reader.skipValue(); 
    } 
    reader.endArray(); 
    System.out.println("loop is break"); // this is not printed as the inner loop is not breaking 
} 
reader.endArray(); 
reader.close(); 

은 내가 예상대로 인쇄된다

36 100 "The 3n + 1 problem" 56717 
................................. 
.................................. 
1049 10108 The Mosquito Killer Mosquitos 49 
1050 10109 Solving Systems of Linear Equations 129 
1051 10110 Light, more light 9414 
1052 10111 Find the Winning Move 365 

이것은 작동하지만 내부 루프가 올바르게 손상되지 않습니다. 내 코드에 어떤 문제가 있습니까? 내 코드가 작동하지 않도록 내가 놓친 부분이 있습니까?

편집 :이 솔루션 결국 (솔루션) : 당신은 hasNext()가 false를 돌려 주었을 경우 skipValue() 또는 * 다음에 전화하지 않으

reader.beginArray(); 
      while (reader.hasNext()) { 
       reader.beginArray(); 
       // read and parse first four elements, checking hasNext() each time for robustness 
       int a = reader.nextInt(); 
       int b = reader.nextInt(); 
       String c = reader.nextString(); 
       int d = reader.nextInt(); 
       System.out.println(a + " " + b + " " + c + " " + d); 
       while (reader.hasNext()) 
        reader.skipValue(); 
       reader.endArray(); 
      } 
      reader.endArray(); 
+0

Java에서 json을 읽는 데 사용할 라이브러리를 지정해주십시오. –

+0

구글에 의해'GSON'입니다 –

답변

2

. GSON documentation은 먼저 누적 값을 권장합니다. 그 테마의 변형은 다음과 같습니다 그 첫번째 4 개 개의 값을 구문 분석 할 수있는 다른 방법의 많음, (예를 들어 첫 번째 목록에 저장, 또는 문자열로 저장할 상황에 대한 의미가 무엇이든 사용할 수있다

reader.beginArray(); 
while (reader.hasNext()) { 
    int position; 
    int a, b, d; // stores your parsed values 
    String c; // stores your parsed values 
    reader.beginArray(); 
    // read and parse first four elements, checking hasNext() each time for robustness 
    for (position = 0; position < 4 && reader.hasNext(); ++ position) { 
     if (position == 0) a = reader.nextInt(); 
     else if (position == 1) b = reader.nextInt(); 
     else if (position == 2) c = reader.nextString(); 
     else if (position == 3) d = reader.nextInt(); 
    } 
    // if position < 4 then there weren't enough values in array. 
    if (position == 4) { // correctly read 
     System.out.println(a + " " + b + " " + c + " " + d); 
    } 
    // skip rest of array, regardless of number of values 
    while (reader.hasNext()) 
     reader.skipValue(); 
    reader.endArray(); 
} 
reader.endArray(); 

하는 것으로 나중에 구문 분석하거나 원하는 것을 선택하십시오. 요점은 배열의 요소 수를 가정하지 않고 규칙을 따르고 각 요소를 읽기 전에 hasNext()를 사용하는 것입니다.

+0

선생님, 완벽하게 작동합니까? 꽤 큰 Json 피드가 있고 안드로이드 내장 JSONparser를 사용하여 json을 파싱했습니다. 성능 향상을 위해 현재'GSON '으로 작업 중입니다. 위의 방법이 가장 빠른 방법이라고 생각하십니까? 또는 추가 최적화를위한 방법이 있습니까? –

+1

최적화 할 수있는 게 많지 않습니다. 위의 코드는 문서별로 GSON을 사용합니다. 이는 수행 할 수있는 최선의 방법입니다. 시간이 많이 걸리는 부분은 GSON의 파서 코드 자체입니다. 어쨌든, 당신은 옳은 질문을하지 않고 있습니다. 조기에 최적화하지 마십시오. 먼저 성능 요구 사항을 충족시키지 못하면 코드를 작동시키고 병목 현상을 찾아 최적화에 대해 생각해보십시오. –

+0

위대한 개념적 조언을 주셔서 감사합니다 :) –