1

使用 GSON,我可以写这个

JsonStreamParser parser = new JsonStreamParser(reader);
System.out.println(parser.next());

如果流由 JSON 对象组成,它会将整个对象打印为字符串。

有没有一种简单的方法可以用杰克逊做到这一点,还是我需要使用我在示例中看到的 while 循环模式?

所以如果第一个对象是: { "id": 1, "name": "Foo", "price": 123, "tags": [ "Bar", "Eek" ], "stock": { "warehouse" :300,“零售”:20 } }

打印的第一行是:

{"id": 1,"name": "Foo","price": 123,"tags": [ "Bar", "Eek" ],"stock": {"warehouse": 300,"retail": 20}}

4

1 回答 1

0

在流模式下,每个 JSON “字符串”都被视为单个令牌,并且每个令牌都将被增量处理,这就是我们称之为“增量模式”的原因。例如,

{
   "name":"mkyong"
}
Token 1 = “{“
Token 2 = “name”
Token 3 = “mkyong”
Token 4 = “}”

您可以编写以下代码来解析上述json文本

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.JsonMappingException;

public class JacksonStreamExample {
   public static void main(String[] args) {

     try {

    JsonFactory jfactory = new JsonFactory();

    /*** read from file ***/
    JsonParser jParser = jfactory.createJsonParser(new File("c:\\user.json"));

    // loop until token equal to "}"
    while (jParser.nextToken() != JsonToken.END_OBJECT) {

        String fieldname = jParser.getCurrentName();
        if ("name".equals(fieldname)) {

          // current token is "name",
                  // move to next, which is "name"'s value
          jParser.nextToken();
          System.out.println(jParser.getText()); // display mkyong

        }

        if ("age".equals(fieldname)) {

          // current token is "age", 
                  // move to next, which is "name"'s value
          jParser.nextToken();
          System.out.println(jParser.getIntValue()); // display 29

        }

        if ("messages".equals(fieldname)) {

          jParser.nextToken(); // current token is "[", move next

          // messages is array, loop until token equal to "]"
          while (jParser.nextToken() != JsonToken.END_ARRAY) {

                     // display msg1, msg2, msg3
             System.out.println(jParser.getText()); 

          }

        }

      }
      jParser.close();

     } catch (JsonGenerationException e) {

      e.printStackTrace();

     } catch (JsonMappingException e) {

      e.printStackTrace();

     } catch (IOException e) {

      e.printStackTrace();

     }

  }

}

输出

mkyong 29

味精 1

味精 2

味精 3

于 2012-08-18T02:27:11.277 回答