how to parse simple json string array to object in java - java

I have a json array as a string in the following format:
[ "Ford", "BMW", "Fiat" ]
which is a legal json string. How am I able to use Gson to save into an object?
When I am trying to use getAsJsonArray(), but I get an error:
java.lang.IllegalStateException: This is not a JSON Array.

Use Gson to parse your Json array.
String input = "[ 'Ford', 'BMW', 'Fiat' ]";
Gson gson = new Gson();
String[] output = gson.fromJson(input, String[].class);
for(String s : output){
System.out.println(s);
}
Output
Ford
BMW
Fiat

You can use this to get value into arraylist using getAsJsonArray() Method
String jsonStr = "['Ford', 'BMW', 'Fiat' ]";
JsonArray root = new JsonParser().parse(jsonStr).getAsJsonArray();
Gson gson = new Gson();
ArrayList<String> staff = new ArrayList<>() ;
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> yourList = new Gson().fromJson(root, listType);
System.out.println(yourList );

Related

How to remove extra escaping quote characters of JsonObject created through Javax

I use javax to create JsonObject and JsonArray from my List<String> and I have a list of Json objects that i want to put in a JsonObject through a JsonArray
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for (String Obj : listOfJsonDfObjects)
jsonArray.add(summaryObj); //{"a":"b"},{"c":"d"}
// this line introduces extra escaping quotes like this {"\"a\"":"\"b\""},{"\"c\"":"\"d\""}
javax.json.JsonObject data = Json.createObjectBuilder()
.add("data", jsonArray.build()).build();
How to avoid these extra quotes escaping characters?
Thanks
You say you have a list of JSON objects, but you really have a list of JSON-formatted strings. To add them to a JsonArray, you need to parse each one into the JSON object model:
public class JsonTest {
public static void main(String[] args) {
List<String> listOfJsonDfObjects = List.of(
"{\"a\":\"b\"}",
"{\"c\":\"d\"}"
);
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for (String summaryObj : listOfJsonDfObjects) {
JsonReader parser = Json.createReader(new StringReader(summaryObj));
jsonArray.add(parser.readObject());
}
JsonObject data = Json.createObjectBuilder()
.add("data", jsonArray.build()).build();
System.out.println(data); // {"data":[{"a":"b"},{"c":"d"}]}
}
}
Using Gson
Gson gson = new Gson();
String json = gson.toJson(listOfJsonDfObjects);
//check json
System.out.println(json);
json = json.replaceAll("\\\\", "");
json = json.replaceAll("\"\\{", "{");
json = json.replaceAll("\\}\"", "}");
//valid json now
System.out.println(json);
A more secure way (to avoid altering original data)
//concatenate objects in list with comma
String json = String.join(",", listOfJsonDfObjects);
//convert to pseudo array
json = "[" + json + "]";
//convert pseudo json array to pseudo json object
json = "{\"data\":" + json + "}";
//cast to json object
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
System.out.println(jsonObject);

Java: Extract json values as individuals

I have this json in java:
jsonObj = {"ps":["2.16.840.1.113883.6.1","LOINC","2.34"]}
jsonObj is response from an API, so I have it as jsonObject and I don't read it from any file.
Is there an easy way to extract all the values as individuals like jsonObj [1]?
You may Use Gson parsing library as below :
Gson gson = new Gson();
// 1. JSON to Java object, read it from a file.
Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);
// 2. JSON to Java object, read it from a Json String.
String jsonInString = "{'name' : 'mkyong'}";
Staff staff = gson.fromJson(jsonInString, Staff.class);
// JSON to JsonElement, convert to String later.
JsonElement json = gson.fromJson(new FileReader("D:\\file.json"), JsonElement.class);
String result = gson.toJson(json);
Gson gson = new Gson();
String jsonInString = "{\"userId\":\"1\",\"userName\":\"Yasir\"}";
User user= gson.fromJson(jsonInString, User.class);
or simply use:
example
JSONObject object = new JSONObject(your_json_response_string);
String IMEICheckResponse = object.getString("getIMEIResult");
for Array use :
//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
You should use a library to deserialize your JSON in a Java Object.
Libraries like GSON, Genson or Jackson.
Once you transform the json in a object, it will have a property called "ps" that will be an array (or a List)

Android json parsing without array name

I have a Json Array as string without name and I want to parse it how can i do it in android ?
My array :
{"emp_info":[
{"id":"1","groupe":"1","professeur":"1"},
{"id":"2","groupe":"2","professeur":"1"}
]}
This is how you can parse it
Assuming your json string is data
JSONObject jsonObj = new JSONObject(data);
JSONArray empInfo = jsonObj.getJSONArray("emp_info");
for(int i = 0; i < empInfo.length(); i++){
JSONObject obj = empInfo.getJSONObject(i);
String id = obj.getString("id");
String groupe = obj.getString("groupe");
String professeur = obj.getString("professeur");
}
The example json you gave has a name, but if it doesn't this is how I do it. Using Gson to parse JSON, I use TypeToken to tell the gson builder it's an array.
List<MyObject> jsonObject = new Gson().fromJson(json, new TypeToken<List<MyObject>>().getType());
With the following code you'll have an object representation of your json array.

How to convert ArrayList of custom class to JsonArray in Java?

I am trying to convert ArrayList of custom class to JsonArray. Below is my code. It executes fine but some JsonArray elements come as zeros even though they are numbers in the ArrayList. I have tried to print them out. Like customerOne age in the ArrayList is 35 but it is 0 in the JsonArray. What could be wrong?
ArrayList<Customer> customerList = CustomerDB.selectAll();
Gson gson = new Gson();
JsonElement element =
gson.toJsonTree(customerList , new TypeToken<List<Customer>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
Below code should work for your case.
List<Customer> customerList = CustomerDB.selectAll();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(customerList, new TypeToken<List<Customer>>() {}.getType());
if (! element.isJsonArray() ) {
// fail appropriately
throw new SomeException();
}
JsonArray jsonArray = element.getAsJsonArray();
Heck, use List interface to collect values before converting it JSON Tree.
As an additional answer, it can also be made shorter.
List<Customer> customerList = CustomerDB.selectAll();
JsonArray result = (JsonArray) new Gson().toJsonTree(customerList,
new TypeToken<List<Customer>>() {
}.getType());
Don't know how well this solution performs compared to the other answers but this is another way of doing it, which is quite clean and should be enough for most cases.
ArrayList<Customer> customerList = CustomerDB.selectAll();
Gson gson = new Gson();
String data = gson.toJson(customerList);
JsonArray jsonArray = new JsonParser().parse(data).getAsJsonArray();
Would love to hear from someone else though if, and then how, inefficient this actually is.
Consider a list of Objects of type Model.class
ArrayList<Model> listOfObjects = new ArrayList<Model>();
List to JSON
String jsonText = new Gson().toJson(listOfObjects);
JSON to LIST
Type listType = new TypeToken<List<Model>>() {}.getType();
List<Model> myModelList = new Gson().fromJson(jsonText , listType);
For Anyone who is doing it in Kotlin, you can get it this way,
val gsonHandler = Gson()
val element: JsonElement = gsonHandler.toJsonTree(yourListOfObjects, object : TypeToken<List<YourModelClass>>() {}.type)
List<> is a normal java object, and can be successfully transformed using standard gson object api.
List in gson looks like this:
"libraries": [
{
//Containing object
},
{
//Containing object
}
],
...
Use google gson jar, Please see sample code below,
public class Metric {
private int id;
...
setter for id
....
getter for id
}
Metric metric = new Metric();
metric.setId(1);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.serializeNulls();
Gson gson = gsonBuilder.create();
System.out.println(gson.toJson(metric));
StringBuffer jsonBuffer = new StringBuffer("{ \"rows\": [");
List<Metric> metrices = new ArrayList<Metric>();
// assume you have more elements in above arraylist
boolean first = true;
for (Metric metric : metrices) {
if (first)
first = false;
else
jsonBuffer.append(",");
jsonBuffer.append(getJsonFromMetric(metric));
}
jsonBuffer.append("]}");
private String getJsonFromMetric(Metric metric) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.serializeNulls();
Gson gson = gsonBuilder.create();
return gson.toJson(metric);
}

Create a JSONArray

How can I create a JSONArray, since creating a JSONObject is quite simple:
JSONObject j = new JSONObject();
j.put("key",value);
Right now I can put another string in the JSONObject, or a string representation of a JSONObject.
But how can I create a JSONArray and insert it to the JSONObject?
But how can I create a JSONArray and insert it to the JSONObject?
You can create JSONArray same like you have tried to create JSONObject.
Creating time:
For example:
JSONArray myArray = new JSONArray();
JSONObject j = new JSONObject();
j.put("key",value);
j.put("array",myArray);
Retrieving time:
you can fetch the value of String or JSONObject or any by their key name. For example:
JSONArray myArray = objJson.getJSONArray("array");
You can do it like:
String[] data = {"stringone", "stringtwo"};
JSONArray json = new JSONArray(Arrays.toString(data));
Or, create a JSONArray object and use the put method(s) to add any Strings you want. To output the result, just use the toString() method.
Why dont you use Gson library its very easy to convert any object into json array, json object
Download Gson library then use like
Gson gson=new Gson();
String json=gson.toJson(object);
if Object is of List object it will create json array
Gson gson = new Gson();
reverse parsing for array --
listObject = gson.fromJson(json,
new TypeToken<List<ClassName>>() {
}.getType());
for single object
object = gson.fromJson(json, ClassName.class);

Categories

Resources