This blog post is about a short example of how to migrate from org.json to Gson. The blog post takes the JSON format example from the blog post. How do you create a watsonx.ai REST client in Spring Boot?
The following JSON format will created with the two different libraries.
{"input": prompt,
"parameters":{"decoding_method":"greedy",
"max_new_tokens: 800,
"min_new_tokens": 0,
"stop_sequence":[\"```\"],
"repetition_penalty": 1.0 },
"model_id":"MODEL_ID",
"project_id":"PROJECT_ID"
}
1. Using org.json
The usage of org.json is broadly distributed, and a lot of documentation is available on various platforms.
// JSON handling
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
...
try {
watsonxRequestJSON = new JSONObject();
watsonxRequestJSON.put("input", getPrompt(question,context));
JSONObject parameters = new JSONObject();
parameters.put("decoding_method", decoding_method);
parameters.put("max_new_tokens", max_new_tokens);
parameters.put("min_new_tokens", min_new_tokens);
parameters.put("beam_width", beam_width);
parameters.put("stop_sequence", stop_sequence);
watsonxRequestJSON.put("parameters", parameters);
watsonxRequestJSON.put("model_id", model_id);
watsonxRequestJSON.put("project_id", project_id);
} catch (JSONException e) {
...
}
2. Using Gson
As you can see in the following code Gson it has mostly the same structure a the org.json JSONObject. Here we don’t need to create an additional JsonArray for the given structure compare to the org.json example.
import com.google.gson.Gson;
import com.google.gson.JsonObject;
...
try {
watsonxRequestJSON = new JsonObject();
watsonxRequestJSON.addProperty("input", prompt);
JsonObject parameters = new JsonObject();
parameters.addProperty("decoding_method", decoding_method);
parameters.addProperty("max_new_tokens", max_new_tokens);
parameters.addProperty("min_new_tokens", min_new_tokens);
parameters.addProperty("beam_width", beam_width);
parameters.addProperty("stop_sequence", stop_sequence);
watsonxRequestJSON.add("parameters",parameters);
watsonxRequestJSON.addProperty("model_id", model_id);
watsonxRequestJSON.addProperty("project_id", project_id);
} catch (Exception e) {
...
}
3. Brief summary
It is not a big dial to migrate and not a lot of changes are needed in the source code.
I hope this was useful to you and let’s see what’s next?
Greetings,
Thomas
#springboot, #java, #json, #gson, #jsonobject, #development

Leave a comment