Java convert Exception object into Json

In this example I will show you how to convert Exception object into Json in Java. For this example I used google gson library.

Example:


package com.testjson;

import com.google.gson.Gson;

public class TestJsonException {

 public static void main(String[] args) {

 Object n = null;

 try {

 n.toString();
 }catch(Exception ex) {

 Gson gson = new Gson();
 //get stack trace elments
 StackTraceElement elements[] = ex.getStackTrace();
 //convert all elements to json string
 System.out.println(gson.toJson(elements));
 }
 }
}

And the result is:
[{“declaringClass”:”com.testjson.TestJsonException”,”methodName”:”main”,”fileName”:”TestJsonException.java”,”lineNumber”:33}]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s