Skip to content

Instantly share code, notes, and snippets.

@lysu
Created August 24, 2017 13:38
Show Gist options
  • Save lysu/d5ae7fbf27cf230876d26fcefbe579d2 to your computer and use it in GitHub Desktop.
Save lysu/d5ae7fbf27cf230876d26fcefbe579d2 to your computer and use it in GitHub Desktop.
test
package test;
import java.io.IOException;
import java.util.Objects;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
public class Main {
public static void main(String[] args) throws IOException {
String content = "{\"a\": {\"test\":\"1\"}}";
Test test = new ObjectMapper().readValue(content, Test.class);
System.out.println(test.getA());
String prop = "a";
String substring = extract(content, prop);
System.out.println(substring);
}
private static String extract(String content, String prop) throws IOException {
String substring = null;
JsonParser parser = new JsonFactory().createParser(content);
while (parser.nextToken() != JsonToken.END_OBJECT) {
if (parser.getCurrentToken() != JsonToken.FIELD_NAME) {
continue;
}
if (!Objects.equals(parser.getText(), prop)) {
parser.skipChildren();
continue;
}
parser.nextToken();
long begin = parser.getCurrentLocation().getCharOffset();
parser.skipChildren();
long end = parser.getCurrentLocation().getCharOffset();
String json = parser.getCurrentLocation().getSourceRef().toString();
substring = json.substring((int) begin - 1, (int) end);
break;
}
return substring;
}
public static class Test {
@JsonDeserialize(using = RawJsonDeserializer.class)
private String a;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
}
public static class RawJsonDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException {
long begin = jp.getCurrentLocation().getCharOffset();
jp.skipChildren();
long end = jp.getCurrentLocation().getCharOffset();
String json = jp.getCurrentLocation().getSourceRef().toString();
return json.substring((int) begin - 1, (int) end);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment