|
| 1 | +package backtraceio.library.common.serialization; |
| 2 | + |
| 3 | +import com.google.gson.TypeAdapter; |
| 4 | +import com.google.gson.stream.JsonReader; |
| 5 | +import com.google.gson.stream.JsonToken; |
| 6 | +import com.google.gson.stream.JsonWriter; |
| 7 | + |
| 8 | +import java.io.IOException; |
| 9 | + |
| 10 | +public class StackTraceElementTypeAdapter extends TypeAdapter<StackTraceElement> { |
| 11 | + |
| 12 | + @Override |
| 13 | + public void write(JsonWriter out, StackTraceElement value) throws IOException { |
| 14 | + if (value == null) { |
| 15 | + out.nullValue(); |
| 16 | + return; |
| 17 | + } |
| 18 | + out.beginObject(); |
| 19 | + out.name("declaring-class").value(value.getClassName()); |
| 20 | + out.name("method-name").value(value.getMethodName()); |
| 21 | + out.name("file-name").value(value.getFileName()); |
| 22 | + out.name("line-number").value(value.getLineNumber()); |
| 23 | + // Do NOT write classLoaderName (for compatibility) |
| 24 | + out.endObject(); |
| 25 | + } |
| 26 | + |
| 27 | + @Override |
| 28 | + public StackTraceElement read(JsonReader in) throws IOException { |
| 29 | + if (in.peek() == JsonToken.NULL) { |
| 30 | + in.nextNull(); |
| 31 | + return null; |
| 32 | + } |
| 33 | + String className = null; |
| 34 | + String methodName = null; |
| 35 | + String fileName = null; |
| 36 | + int lineNumber = -1; |
| 37 | + |
| 38 | + in.beginObject(); |
| 39 | + while (in.hasNext()) { |
| 40 | + String name = in.nextName(); |
| 41 | + switch (name) { |
| 42 | + case "declaring-class": |
| 43 | + className = in.nextString(); |
| 44 | + break; |
| 45 | + case "method-name": |
| 46 | + methodName = in.nextString(); |
| 47 | + break; |
| 48 | + case "file-name": |
| 49 | + if (in.peek() == JsonToken.NULL) { |
| 50 | + in.nextNull(); |
| 51 | + fileName = null; |
| 52 | + } else { |
| 53 | + fileName = in.nextString(); |
| 54 | + } |
| 55 | + break; |
| 56 | + case "line-number": |
| 57 | + lineNumber = in.nextInt(); |
| 58 | + break; |
| 59 | + // Ignore any unknown fields (including classLoaderName) |
| 60 | + default: |
| 61 | + in.skipValue(); |
| 62 | + } |
| 63 | + } |
| 64 | + in.endObject(); |
| 65 | + return new StackTraceElement(className, methodName, fileName, lineNumber); |
| 66 | + } |
| 67 | +} |
0 commit comments