Json4s not serializing Java classes
Asked Answered
S

3

6

I have some scala code that needs to be able to serialize/deserialize some Java classes using Json4s.

I am using "org.json4s" %% "json4s-ext" % "4.0.5" and "org.json4s" %% "json4s-jackson" % "4.0.5" though I have also tried with the 3.6.7 version.

Model Code (Java):

import com.fasterxml.jackson.annotation.JsonProperty;

public class Blah {
    @JsonProperty("what")
    public final String what;

    public Blah() {
        this(null);
    }
    public Blah(String what) {
        this.what = what;
    }
}

Serialization (Scala):

import org.json4s.DefaultFormats
import org.json4s.jackson.Serialization

println(Serialization.write(new Blah("helloooo!!!!"))(DefaultFormats))

It only ever prints out: {}.

I understand I can write a CustomSerializer for each Java class but I have a lot of Java classes and would really like to avoid doing that. Any ideas on how to make this work?

Spencerspencerian answered 10/5, 2022 at 17:43 Comment(3)
BEWARE: json4s is vulnerable under DoS/DoW attacks!Ecumenicist
BEWARE: @AndriyPlokhotnyuk is constantly promoting his own JSON library.Honniball
Tim, if you are using json4s really then I feel sorry for your clients, who are misled by your decisions. Can it be explanation why you are hidden under some nick here?Ecumenicist
S
3

Json4s is the Json library for Scala. To work with Java objects, it is recommended to directly use Jackson. See this question here

Json4s uses jackson only as a parser, and after parsing, it all works by matching from Json4s AST to Scala objects.

If you want to work with Java collections, you should use Jackson directly

So, we can get the mapper which is an object of Jackson's ObjectMapper and use it normally -

import org.json4s.jackson.JsonMethods

println(JsonMethods.mapper.writeValueAsString(new Blah("helloooo!!!!")))
Shoelace answered 14/5, 2022 at 10:2 Comment(0)
T
0

Try to add getter method for your what property

Tulley answered 11/5, 2022 at 16:40 Comment(1)
I added a public String getWhat() method and it still didn't work. Also tried adding @JsonGetter annotation to it but I got the same result.Spencerspencerian
F
0

Json4s ignores any JsonProperty annotation and requires both a constructor parameter and a Scala case-class style getter method for each property of your Java model class. In the example above that would look like:

public class Blah {
    private final String what;

    public String what() {
        return what;
    }

    public Blah() {
        this(null);
    }
    public Blah(String what) {
        this.what = what;
    }
}
Fob answered 13/5, 2022 at 10:6 Comment(2)
I still get a {} with that code.Spencerspencerian
The above is working for sure... but @Shoelace is right. If you are just dealing with Java classes you're better not using Json4sFob

© 2022 - 2024 — McMap. All rights reserved.