Parser for JSON in Servlet just like SAX for XML
Asked Answered
A

3

2

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.

Andrus answered 18/5, 2012 at 18:14 Comment(0)
S
2

You should use the Google GSON parser in Java

See also the Gson User Guide.

Spartacus answered 18/5, 2012 at 18:22 Comment(0)
S
2

There is also Jackson:

http://jackson.codehaus.org/

Soren answered 18/5, 2012 at 18:25 Comment(0)
Q
1

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.

Quita answered 11/7, 2013 at 16:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.