In scala there's an API to create json string without the need to have existing class to be encoded into json, for example:
val json: JsValue = Json.obj(
"name" -> "Watership Down",
"location" -> Json.obj("lat" -> 51.235685, "long" -> -1.309197),
"residents" -> Json.arr(
Json.obj(
"name" -> "Fiver",
"age" -> 4,
"role" -> JsNull
),
Json.obj(
"name" -> "Bigwig",
"age" -> 6,
"role" -> "Owsla"
)
)
)
I know it is verbose, but sometimes it is handy.
Do Java has similar library, or I should have a class to be converted to Json String?
If I am not wrong you were asking for a JSON object builder. This will help you I guess.
import org.json.simple.JSONObject;
JSONObject obj=new JSONObject();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
obj.put("nickname",null);
System.out.print(obj);
So basically you have to include the latest .jar file in your class path and you are good to go.
This would also help. this is distributed mainly via maven.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With