Parser for JSON in Servlet just like SAX for XML

我只是一个虾纸丫 提交于 2019-12-11 04:08:56

问题


I am using JDOM SAX parser for parsing an external XML file. However i need to parse a JSON in the same servlet. Can anyone suggest parse similar to SAX.


回答1:


You should use the Google GSON parser in Java

See also the Gson User Guide.




回答2:


There is also Jackson:

http://jackson.codehaus.org/




回答3:


You can do it with GSON:

import java.io.IOException;
import java.math.BigDecimal;

import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;

public class JsonProcessor {

  public void parse(JsonReader reader) throws IOException {
    onStartDocument();
    while (true) {
      JsonToken token = reader.peek();
      switch (token) {
      case BEGIN_ARRAY:
        reader.beginArray();
        onBeginArray();
        break;
      case END_ARRAY:
        reader.endArray();
        onEndArray();
        break;
      case BEGIN_OBJECT:
        reader.beginObject();
        onBeginObject();
        break;
      case END_OBJECT:
        reader.endObject();
        onEndObject();
        break;
      case NAME:
        String name = reader.nextName();
        onName(name);
        break;
      case STRING:
        String s = reader.nextString();
        onString(s);
        break;
      case NUMBER:
        String n = reader.nextString();
        onNumber(new BigDecimal(n));
        break;
      case BOOLEAN:
        boolean b = reader.nextBoolean();
        onBoolean(b);
        break;
      case NULL:
        reader.nextNull();
        onNull();
        break;
      case END_DOCUMENT:
        onEndDocument();
        return;
      }
    }
  }

  public void onStartDocument() {
  }

  public void onBeginObject() {
  }

  public void onEndObject() {
  }

  public void onBeginArray() {
  }

  public void onEndArray() {
  }

  public void onName(String name) {
  }

  public void onNumber(BigDecimal n) {
  }

  public void onString(String s) {
  }

  public void onNull() {
  }

  public void onEndDocument() {
  }

  public void onBoolean(boolean b) {
  }
}

Note: If you are using android api >= 11 then you can use the:

import android.util.JsonReader;
import android.util.JsonToken;

classes instead of GSON.



来源:https://stackoverflow.com/questions/10657725/parser-for-json-in-servlet-just-like-sax-for-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!