71

Is it possible to get the whole object from debugger as Json? There is an option View text but can I somehow View JSON?

Michu93
  • 5,058
  • 7
  • 47
  • 80

10 Answers10

75

EDIT: as noted in the comments, this is not perfect, as for some variables you will get a "stackoverflow" response

As suggested by @Mr Han's answer, here's how you can do this:

Add a new way to view objects in Intellij debugger as json by

  • Going to File | Settings | Build, Execution, Deployment | Debugger | Data Views | Java Type Renderers
  • Click + to add new renderer
  • Call it JSON renderer
  • Supply java.lang.Object for Apply renderer to objects of type
  • Choose Use following expression: and supply an expression like so:
if (null == this || this instanceof String)
  return this;

new com.google.gson.GsonBuilder().setPrettyPrinting().create().toJson(this);
  • Click OK
  • Now when you choose Copy Value on a variable, it will copy as json. enter image description here

Note: If you don't want to change default behaviour, create a "default" renderer also with "use default renderer" settings, and put it first in the list, it will use that as default and you can switch to JSON on demand by right click on debugged variable -> use renderer: JSON Renderer.

Brad Parks
  • 66,836
  • 64
  • 257
  • 336
  • 1
    I get sometimes for certain objects, StackOverflow or OutOfMemory exception. Otherwise works like charm. Thanks. – Dileepa Feb 24 '20 at 09:18
  • Yeah I see the same @Dileepa - but I think this is true of any approach like this? I tried making the code catch exceptions and return the original "this", but that didnt seem to help – Brad Parks Feb 24 '20 at 12:25
  • 1
    Accepted answer doesn't work for me, but this does. Also, I like how it's a no plugin solution. Just edit settings, no download plugin hassle. – Nick Zafiridis May 14 '20 at 09:28
  • I wanted to use the inbuilt feature of IntelliJ for such tasks and this answer does exactly that. Thank god I am not using a plugin for such needs. – MrKumar Oct 01 '20 at 19:01
  • I get the JSON value of the main object but the child object fields are all empty instead of getting copied into JSON – firstpostcommenter May 26 '21 at 12:20
  • yeah it's not perfect - i actually don't use it anymore as I found the stack overflow was too annoying – Brad Parks May 26 '21 at 13:14
  • 7
    I get Method threw 'java.lang.ClassNotFoundException' exception. – dewijones92 Dec 02 '21 at 14:34
  • yeah this solution requires the [google gson library](https://mvnrepository.com/artifact/com.google.code.gson/gson), and you may be better off going with [this solution](https://stackoverflow.com/a/69802068/26510) which builds on mine! – Brad Parks Dec 02 '21 at 19:02
  • I have the gson library in my project and I'm still getting a ClassNotFoundException. – Austin Brown Mar 22 '22 at 13:28
  • do you have it as a dev dependency ? – Brad Parks Mar 22 '22 at 16:28
  • The code section is not clear, can you format it properly? Despite this I have a bigger issue since I'm getting `Unable to evaluate the expression Method threw 'com.google.gson.JsonIOException' exception.` a solution that requires a project dependency is hardly a solution to this question imho. – Aspiring Dev Apr 06 '23 at 14:49
25

Alternatively, as seen here, you can use the following piece of code in your debug watcher:

new ObjectMapper()
    .setSerializationInclusion(JsonInclude.Include.NON_NULL)
    .writerWithDefaultPrettyPrinter()
    .writeValueAsString( myObject )
Rlarroque
  • 1,900
  • 1
  • 17
  • 27
18

You can try this code fragment into the Evaluate Expression(Alt + F8) on IntelliJ :

new com.fasterxml.jackson.databind.ObjectMapper() .registerModule(new com.fasterxml.jackson.datatype.jsr310.JavaTimeModule()) .disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .writerWithDefaultPrettyPrinter() .writeValueAsString( myObject );

image IntelliJ

Luth Sanches
  • 191
  • 1
  • 3
7

You could use the Show as ... plugin for IntelliJ.

A small plugin to display formatted data out of the debugger and console.

Uses IntelliJ's build-in formatting capabilities. No more need to copy values from debugger or console to a file to format them there. Following formats are supported: JSON, SQL, XML, Base64 encoded JSON, Base64 encoded text

Community
  • 1
  • 1
glytching
  • 44,936
  • 9
  • 114
  • 120
  • 7
    Unforunately it soesn't seem to work correctly while debugging as pointed out in the comment section of the plugin. I tried myself without success. – Rlarroque Sep 20 '19 at 12:58
  • As people say in the review of the plugin and in multiple comments here on StackOverflow, this plugin does not work (anymore?). What a shame that such functionality is not out-of-the-box in IntelliJ IDEA :( – Honza Zidek Nov 01 '21 at 19:50
6

If you have gson dependency in your project you can create a watch variable

new GsonBuilder().setPrettyPrinting().create().gson.toJson(myObject)

where myObject is your object.

bluelurker
  • 1,353
  • 3
  • 19
  • 27
  • In my case `new com.google.gson.GsonBuilder().setPrettyPrinting().create().toJson(myObject)` was what worked while debugging. – Granger Jun 09 '23 at 20:58
4

Just follow it : File | Settings | Build, Execution, Deployment | Debugger | Data Views | Java Type Renderers, click + to add new render , copy is OK :) u can choose another jar to format it

And now , Apply, join it ~

Mr Han
  • 59
  • 2
4

Follow the instructions of @BradParks, and use the following expression.

For me it did not work without fully-qualified class names. I also added some modifications to the ObjectMapper. For some reason which I don't understand, even if I have Apply renderers to object of type set to java.lang.Object, I needed to typecast this as (Object)this when used as a parameter of the writeValueAsString() method.

if (this == null 
|| this instanceof CharSequence 
|| this instanceof Number 
|| this instanceof Character 
|| this instanceof Boolean 
|| this instanceof Enum) {
// Here you may add more sophisticated test which types you want to exclude from the JSON conversion.
    return this;
}

new com.fasterxml.jackson.databind.ObjectMapper() 
        .registerModule(new com.fasterxml.jackson.datatype.jsr310.JavaTimeModule())
        .disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
        .setVisibility(
                com.fasterxml.jackson.annotation.PropertyAccessor.FIELD, 
                JsonAutoDetect.Visibility.ANY)
        .setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL)
        .writerWithDefaultPrettyPrinter()         
        .writeValueAsString((Object)this);
Honza Zidek
  • 9,204
  • 4
  • 72
  • 118
  • Gave me a ClassNotFoundException. – Austin Brown Mar 22 '22 at 13:27
  • @AustinBrown on which of the classes? I would also *guess* that the jackson library must be included in your project in order this to work. – Honza Zidek Mar 23 '22 at 09:14
  • It's on the jackson library. I do have the jackson library in my project, but for some reason I still get the exception. – Austin Brown Mar 23 '22 at 22:19
  • @AustinBrown On which class exactly? I noticed that in my code the `JsonAutoDetect` class is not fully qualified (but it worked for me) - could this be the problem? – Honza Zidek Mar 24 '22 at 09:53
  • implementation("com.fasterxml.jackson.core:jackson-databind:2.13.2") implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.2") – nutella_eater Mar 24 '22 at 11:21
1

Use Intellij plugin Debug Variable Extractor More information - https://plugins.jetbrains.com/plugin/16362-debug-variable-extractor

New Bee
  • 390
  • 3
  • 10
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/32928993) – ThomasIsCoding Oct 13 '22 at 08:01
  • @ThomasIsCoding I have already provided Intellij plugin name in my answer. Any one can search this plugin and install it. No need to navigate to the link. – New Bee Oct 20 '22 at 10:25
  • It gives me Timeout on the first run, but when I try again it works very well! This is the best solution for me – MAvim Aug 18 '23 at 10:23
0

In case someone is having hard time to make the renderers work for more complex objects - below you can find a combined JSON renderer from:

The following renderer helped me to identify multiple fields with the same name in the class hierarchy, so I could change that.

Initially I was having IllegalArgumentException for serialization of a nested object that I wasn't able to analyse.

If there is an issue during serialization, with this renderer you can find the stack trace from the exception that you need to fix in the console.

Good luck!


if (null == this)
    return "null";

if (this instanceof CharSequence
        || this instanceof Number
        || this instanceof Character
        || this instanceof Boolean
        || this instanceof Enum) {
    // Here you may add more sophisticated test which types you want to exclude from the JSON conversion.
    return this;
}
try {
    String json = new GsonBuilder().setPrettyPrinting().create().toJson(this);
    return json;
} catch (Exception e) {
    e.printStackTrace();
}
Martin Patsov
  • 366
  • 5
  • 10
0

worked for me: rightclick on the variable itself to select "Evaluate Expression"

In the popup with the evaluated expression you can right click the result and select "Copy JSON"

felicityiz
  • 11
  • 4