Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a JSON Literal in java without need for existing class

Tags:

java

json

scala

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?

like image 657
Muhammad Hewedy Avatar asked Apr 29 '26 08:04

Muhammad Hewedy


1 Answers

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.

like image 126
Vamshi Krishna Alladi Avatar answered May 01 '26 22:05

Vamshi Krishna Alladi



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!