I am trying to create below JSON in Java.
"data": {
"keys": ["access_token"]
}
I have tried below code for same
JSONObject jsonObjSend = new JSONObject();
JSONObject data = new JSONObject();
JSONArray keys = new JSONArray();
keys.add("access_token");
jsonObjSend.put("keys", keys);
data.put("data",keys);
System.out.println(obj.toString());
you are doing it wrongly. you need to add data to jsonObjSend check this.
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) {
JSONObject jsonObjSend = new JSONObject();
JSONObject data = new JSONObject();
JSONArray keys = new JSONArray();
keys.put("access_token");
data.put("keys", keys);
jsonObjSend.put("data",data);
System.out.println(jsonObjSend.toString());
}
}
You can achieve it by using google gson Json.
Have a look to the sample code
JsonObj obj = new JsonObj();
Data data = new Data();
String keys[] = {"access_token"};
data.setKeys(keys);
obj.setData(data);
System.out.println("==================>>>"+gson.toJson(obj));
class JsonObj{
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
class Data{
private String[] keys;
public String[] getKeys() {
return keys;
}
public void setKeys(String[] keys) {
this.keys = keys;
}
}
Please mind the desired output is not a valid JSON:
"data": {
"keys": [
"access_token"
]
}
A valid JSON would be:
{
"data": {
"keys": [
"access_token"
]
}
}
Once you are using the org.json library to work with JSON, you might find the following code useful:
JSONObject root = new JSONObject();
JSONObject data = new JSONObject();
root.put("data", data);
JSONArray keys = new JSONArray();
keys.put("access_token");
data.put("keys", keys);
String json = root.toString();
It will produce this JSON:
{"data": {"keys": ["access_token"]}}
I have an interface (called Content) and a couple of classes that implement that interface (e.g. ContentVideo, ContentAd...). I receive a JSON Object that contains a list of those objects. I started out deserializing those objects manually in seperate classes, but recently came across GSON, which would simplify this process immensely. But I'm not sure how to implement this.
Here's ContentVideoJSONParser
public ArrayList<ContentVideo> parseJSON(String jsonString) {
ArrayList<ContentVideo> videos = new ArrayList<>();
JSONArray jsonArr = null;
Gson gson = new Gson();
try {
jsonArr = new JSONArray(jsonString);
for(int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
ContentVideo cv = gson.fromJson(jsonObj.toString(), ContentVideo.class);
videos.add(cv);
}
} catch (JSONException e) {
e.printStackTrace();
}
return videos;
}
ContentAdJSONParser looks exactly the same, except for returning an ArrayList of ContentAd objects and this line to retrieve the object:
ContentAd ca = gson.fromJson(jsonObj.toString(), ContentAd.class);
What's the easiest way to combine those to classes into one? Note: one JSON object only contains one class, either ContentVideo or ContentAd. They are not mixed like in other SO questions, which would require a TypeAdapter.
This seems to be a straightforward problem but I can't figure it out. Thanks for your help.
Something like this perhaps?
public <T extends Content> ArrayList<T> parseJSON(String jsonString, Class<T> contentClass) {
ArrayList<T> contents = new ArrayList<>();
JSONArray jsonArr = null;
Gson gson = new Gson();
try {
jsonArr = new JSONArray(jsonString);
for(int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
T content = gson.fromJson(jsonObj.toString(), contentClass);
contents.add(content);
}
} catch (JSONException e) {
e.printStackTrace();
}
return contents;
}
What I am trying to do, and I don't know whether this is possible, is to get the class type of an object, and then use it in a declaration. I am using the Gson library for Json Conversion and I want to create a method that can take any object Arraylist type and convert it into a JsonArray. What I have below is code. Arraylist of type X will are casted down to type Object and than passed to the method below. The INSERT_CLASS_HERE should be dynamic based on the Object type.
public static JsonArray getJsonArray(List<Object> list , Class theClass){
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(list, new TypeToken<List<INSERT_CLASS_TYPE_HERE>>() {}.getType());
if (! element.isJsonArray()) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
JsonArray jsonArray = element.getAsJsonArray();
return jsonArray;
}
What I tried was the following but this isn't correct syntax and will throw errors
public static JsonArray getJsonArray(List<Object> list , Class theClass){
if(list.size() == 0) return null;
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(list, new TypeToken<List<theClass>>() {}.getType());
if (! element.isJsonArray()) {
// fail appropriately
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
JsonArray jsonArray = element.getAsJsonArray();
return jsonArray;
}
1) Is this possible to do, and if not why not?
2) If it is not, how can this be achieved?
Thank you!
Why are you passing in a type value? That should not be required.
public static JsonArray getJsonArray(List<Object> list){
if(list.size() == 0) return null;
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(list);
JsonArray jsonArray = element.getAsJsonArray();
return jsonArray;
}
Better yet to avoid casting you can do the following
public static <T> JsonArray getJsonArray(List<T> list){
if(list.size() == 0) return null;
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(list);
JsonArray jsonArray = element.getAsJsonArray();
return jsonArray;
}
It seems what you are trying to do is along the lines of Java generics.
This should be fairly simply to do using generics:
public static <T> JsonArray getJsonArray(List<T> list){
if(list.size() == 0) return null;
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(list, new TypeToken<List<T>>() {}.getType());
//Not familiar with gson, but you might be able to just use T here instead
Try modifying your method signature like this:
public static <T> JsonArray getJsonArray(List<Object> list, Class<T> theClass )
You should then be able to do this:
new TypeToken<List<T>>
I'm using this method to parse a JSON string, but it is too slow... is there a better way to do it?
Thanks
synchronized private void parseCategories(String response){
try{
JSONArray categoriesJSONArray = new JSONArray (response);
// looping through All Contacts
for(int i = 0; i < categoriesJSONArray.length(); i++){
JSONObject currentCategory = categoriesJSONArray.getJSONObject(i);
String label="";
String categoryId="";
// Storing each json item in variable
if(currentCategory.has("label"))
label = currentCategory.getString("label");
if(currentCategory.has("id"))
categoryId = currentCategory.getString("id");
if(
label!=null &&
categoryId!=null
)
{
Category toAdd = new Category(categoryId, label);
categories.add(toAdd);
}
}
//Alphabetic order
Collections.sort(
categories,
new Comparator<Feed>() {
public int compare(Feed lhs, Feed rhs) {
return lhs.getTitle().compareTo(rhs.getTitle());
}
}
);
Intent intent = new Intent("CategoriesLoaded");
LocalBroadcastManager.getInstance(mAppContext).sendBroadcast(intent);
}catch (JSONException e) {
e.printStackTrace();
}
}
Here's try following code to start with. You would need Gson library for it.
Gson gson=new Gson();
MyBean myBean=gson.fromJson(response);
Note: Here MyBean class contains the fields present in you json string for e.g. id, along with getter and setters. Rest of all is handled by Gson.
Here's a quick demo.
import com.google.gson.annotations.SerializedName;
public class Box {
#SerializedName("id")
private String categoryId;
// getter and setter
}
Say you JSON looks as following:
{"id":"A12"}
You can parse it as follows:
class Parse{
public void parseJson(String response){
Gson gson=new Gson();
Box box=gson.fromJson(response,Box.class);
System.out.println(box.getCategoryId());
}
}
Output :
A12
For more on Gson visit here
Use GSON library. You can convert your object to json string like the following example:
MyClass MyObject;
Gson gson = new Gson();
String strJson = gson.toJson(MyObject);
I have a function which is returning Data as List in java class. Now as per my need, I have to convert it into Json Format.
Below is my function code snippet:
public static List<Product> getCartList() {
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
}
return cartList;
}
I tried To convert into json by using this code but it is giving type mismatch error as function is of type List...
public static List<Product> getCartList() {
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
}
Gson gson = new Gson();
// convert your list to json
String jsonCartList = gson.toJson(cartList);
// print your generated json
System.out.println("jsonCartList: " + jsonCartList);
return jsonCartList;
}
Please help me resolve this.
Using gson it is much simpler. Use following code snippet:
// create a new Gson instance
Gson gson = new Gson();
// convert your list to json
String jsonCartList = gson.toJson(cartList);
// print your generated json
System.out.println("jsonCartList: " + jsonCartList);
Converting back from JSON string to your Java object
// Converts JSON string into a List of Product object
Type type = new TypeToken<List<Product>>(){}.getType();
List<Product> prodList = gson.fromJson(jsonCartList, type);
// print your List<Product>
System.out.println("prodList: " + prodList);
public static List<Product> getCartList() {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", "1");
formDetailsJson.put("name", "name1");
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("forms", jsonArray);//Here you can see the data in json format
return cartList;
}
you can get the data in the following form
{
"forms": [
{ "id": "1", "name": "name1" },
{ "id": "2", "name": "name2" }
]
}
Try these simple steps:
ObjectMapper mapper = new ObjectMapper();
String newJsonData = mapper.writeValueAsString(cartList);
return newJsonData;
ObjectMapper() is com.fasterxml.jackson.databind.ObjectMapper.ObjectMapper();
i wrote my own function to return list of object for populate combo box :
public static String getJSONList(java.util.List<Object> list,String kelas,String name, String label) {
try {
Object[] args={};
Class cl = Class.forName(kelas);
Method getName = cl.getMethod(name, null);
Method getLabel = cl.getMethod(label, null);
String json="[";
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
if(i>0){
json+=",";
}
json+="{\"label\":\""+getLabel.invoke(o,args)+"\",\"name\":\""+getName.invoke(o,args)+"\"}";
//System.out.println("Object = " + i+" -> "+o.getNumber());
}
json+="]";
return json;
} catch (ClassNotFoundException ex) {
Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
System.out.println("Error in get JSON List");
ex.printStackTrace();
}
return "";
}
and call it from anywhere like :
String toreturn=JSONHelper.getJSONList(list, "com.bean.Contact", "getContactID", "getNumber");
Try like below with Gson Library.
Earlier Conversion List format were:
[Product [Id=1, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=32 inches, Price=33500.5, Stock=17.0], Product [Id=2, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=42 inches, Price=41850.0, Stock=9.0]]
and here the conversion source begins.
//** Note I have created the method toString() in Product class.
//Creating and initializing a java.util.List of Product objects
List<Product> productList = (List<Product>)productRepository.findAll();
//Creating a blank List of Gson library JsonObject
List<JsonObject> entities = new ArrayList<JsonObject>();
//Simply printing productList size
System.out.println("Size of productList is : " + productList.size());
//Creating a Iterator for productList
Iterator<Product> iterator = productList.iterator();
//Run while loop till Product Object exists.
while(iterator.hasNext()){
//Creating a fresh Gson Object
Gson gs = new Gson();
//Converting our Product Object to JsonElement
//Object by passing the Product Object String value (iterator.next())
JsonElement element = gs.fromJson (gs.toJson(iterator.next()), JsonElement.class);
//Creating JsonObject from JsonElement
JsonObject jsonObject = element.getAsJsonObject();
//Collecting the JsonObject to List
entities.add(jsonObject);
}
//Do what you want to do with Array of JsonObject
System.out.println(entities);
Converted Json Result is :
[{"Id":1,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"32 inches","Price":33500.5,"Stock":17.0}, {"Id":2,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"42 inches","Price":41850.0,"Stock":9.0}]
Hope this would help many guys!
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<String> ls =new ArrayList<String>();
for(product cj:cities.getList()) {
ls.add(cj);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", cj.id);
formDetailsJson.put("name", cj.name);
jsonArray.put(formDetailsJson);
}
responseDetailsJson.put("Cities", jsonArray);
return responseDetailsJson;
You can use the following method which uses Jackson library
public static <T> List<T> convertToList(String jsonString, Class<T> target) {
if(StringUtils.isEmpty(jsonString)) return List.of();
return new ObjectMapper().readValue(jsonString, new ObjectMapper().getTypeFactory().
constructCollectionType(List.class, target));
} catch ( JsonProcessingException | JSONException e) {
e.printStackTrace();
return List.of();
}
}
if response is of type List , res.toString() is simply enough to convert to json or else we need to use
ObjectMapper mapper = new ObjectMapper();
String jsonRes = mapper.writeValueAsString(res);