Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON object from java ObjectName.toString

I have a java object witch generates this output when i type objectName.toString() :

Bus [id=1, nextStationID=0, previousStationID=0]

Is there a JSON parser that lets me make a JSON from the string that my object generates? something like: JsonObject x = new JsonObject(busObject.toString())

It is important for me to generate it from the string that i get when calling the .toString method.

Any help is appreciated.

like image 390
Mihai Avatar asked Mar 26 '26 05:03

Mihai


1 Answers

A JSON parser's goal is to make a JSON string from an Object or to create an Object from a JSON string.

In your own answer, manually making a JSON string from your Object is ok but I think that using a JSON parser will make your code easiest to maintain and more efficient.

You can use this toString() method :

public String toString() {
    Gson gson = new Gson();
    return gson.toJson(this, Bus.class);
}

With this solution, even if you remove or add fields in your class, the toString() method still be ok.

To finish, if you want to convert your object to a JSONObject, I advise you to create a method like toJSONObject and to manually make the conversion inside it.

like image 130
mithrop Avatar answered Mar 28 '26 19:03

mithrop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!