How to convert list data into json in java - java

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);

Related

Java: Get value from a Json string (Set<String>)

I'm using this method that returns a Set<String> but in fact what I got is a Json string like this
[
{
"id":"Id1"
},
{
"id":"Id2",
"title":"anyTitle"
}
]
My goal is to get the value of key "id". I've also made a java bean to map the data:
public class Data {
private String id;
private String title;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
I tryied to parse using gson but all I can get is an error: Cannot cast 'java.util.LinkedHashMap$LinkedKeyIterator' to 'com.google.gson.stream.JsonReader'
So, obviously I'm doing something wrong:
Set<String> availableData = getData(); //this method returns a json string
Iterator<String> itr = availableData.iterator();
while (itr.hasNext()) {
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(itr.next());
Data data = gson.fromJson(object, Data.class);
}
update: The actual error is: Type mismatch Can't assign com.google.common.collect.Maps$TransformedEntriesMap to java.lang.String
In that line you pass an iterator:
JsonObject object = (JsonObject) parser.parse((JsonReader) itr);
But you should pass a next element:
JsonObject object = (JsonObject) parser.parse(itr.next());
In addition you got an extra comma in you JSON.
You can replace the whole block with that line:
Data data = gson.fromJson(itr.next(),Data.class)
Use Jackson mapper. You can directly convert it into an object and retrieve through getters.
ObjectMapper objectMapper = new ObjectMapper();
String carJson =
"{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";
try {
Car car = objectMapper.readValue(carJson, Car.class);
System.out.println("car brand = " + car.getBrand());
System.out.println("car doors = " + car.getDoors());
} catch (IOException e) {
e.printStackTrace();
}
So, following this related issue: https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/5154, finally I map this using JSONArray and streams from java8
Set<String> availableData = getData();
JSONArray dataArray = new JSONArray(availableData);
List<Object> dataList = dataArray.toList();
Object o = dataList.stream()
.filter(c -> ((Map) c).get("id").toString().contains("Id1"))
.findFirst().orElse(null);
return ((Map)o).get("id").toString();
Maybe you want to known how to use Gson to unserialized json to java object.
Here are two ways I can give you.
public void parse() {
String jsonString = "[\n" +
" {\n" +
" \"id\":\"Id1\"\n" +
" },\n" +
" {\n" +
" \"id\":\"Id2\",\n" +
" \"title\":\"anyTitle\"\n" +
" }\n" +
"]";
Gson gson = new Gson();
// Use Gson Type
Type setType = new TypeToken<HashSet<Data>>(){}.getType();
Set<Data> dataSet = gson.fromJson(jsonString, setType);
// Print [Data{id='Id2', title='anyTitle'}, Data{id='Id1', title='null'}]
System.out.println(dataSet);
// Use Java Array
Data[] dataArray = gson.fromJson(jsonString, Data[].class);
// Print [Data{id='Id1', title='null'}, Data{id='Id2', title='anyTitle'}]
System.out.println(Arrays.toString(dataArray));
}

How to parsing JSON like this?

I have json data format like
{
"status":200,
"message":"ok",
"response": {"result":1, "time": 0.0123, "values":[1,1,0,0,0,0,0,0,0]
}
}
I want to get one value of values array and put it on textView in eclipse. Look my code in eclipse
protected void onPostExecute (String result){
try {
JSONobject json = new JSONObject(result);
tv.setText(json.toString(1));
}catch (JSONException e){
e.printStackTrace();
}
}
You can use GSON
Create a POJO for your response
public class Response{
private int result;
private double time;
private ArrayList<Integer> values;
// create SET's and GET's
}
And then use GSON to create the object you desire.
protected void onPostExecute (String result){
try {
Gson gson = new GsonBuilder().create();
Response p = gson.fromJson(result, Response.class);
tv.setText(p.getValues());
}catch (JSONException e){
e.printStackTrace();
}
}
You can use jackson library for json parsing.
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readTree(json);
map.get("key");
You can use readTree if you know json is an instance of JSONObject class else use typeref and go with readValue to get the map.
protected void onPostExecute (String result){
try {
JSONObject json = new JSONObject(result);
JSONObject resp = json.getJSONObject("response");
JSONArray jarr = resp.getJSONArray("values");
tv.setText(jarr.get(0).toString(1));
}catch (JSONException e){
e.printStackTrace();
}
}

Java - Get multiple JSON values and turn into String

How would I get all the "name" values and turn them into a String?
So for example if I'd do the following:
System.out.println(value[1]);
It would print out name1.
Here is what I have so far:
JSON:
[
{
"name":"name1"
},
{
"name":"name2",
"changedToAt":1470659096000
},
{
"name":"name3",
"changedToAt":1473435817000
}
]
Java code:
try {
String UUID = p.getUniqueId().toString();
String slimUUID = UUID.replace("-", "");
InputStream in = new URL("https://api.mojang.com/user/profiles/" + slimUUID + "/names").openStream();
String json = IOUtils.toString(in);
IOUtils.closeQuietly(in);
try {
JSONParser parser = new JSONParser();
JSONObject jsonparse = (JSONObject) parser.parse(json);
//get "name" values and turn into String
} catch (ParseException e) {
System.out.println(e.getMessage());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
You need to iterate over array and accumulate all name values into array of Strings.
So below is working source code:
JsonArray jsonObject = new JsonParser()
.parse(json)
.getAsJsonArray();
List<String> names = new ArrayList<>();
for (JsonElement jsonElement : jsonObject) {
names.add(jsonElement.getAsJsonObject().get("name").getAsString());
}
//now you can use as you wish, by index
System.out.println(names.get(1));//returns "name2"
Using the URL from your comment and Java 8 Stream API I've built this main method:
public static void main(final String[] args) throws ParseException, MalformedURLException, IOException {
final String url = "https://api.mojang.com/user/profiles/c8570e47605948d3a3cbe3ec3a681cc0/names";
final InputStream in = new URL(url).openStream();
final String json = IOUtils.toString(in);
IOUtils.closeQuietly(in);
final JSONParser parser = new JSONParser();
final JSONArray jsonparse = (JSONArray) parser.parse(json);
System.out.println(jsonparse);
System.out.println();
final List<String> names = (ArrayList<String>) jsonparse.stream().map((obj) -> {
final JSONObject object = (JSONObject) obj;
return (String) object.getOrDefault("name", "");
}).peek(System.out::println).collect(Collectors.toList());
}
Try My library: abacus-common. All the above can be replaced with:
List<Map<String, Object>> resp = HttpClient.of("https://api.mojang.com/user/profiles/" + slimUUID + "/names").get(List.class);
List<String> names = resp.stream().map(m -> (String) (m.get("name"))).collect(Collectors.toList());
By the way, if slimUUID is equal to: UUID.randomUUID().toString().replaceAll("-", ""). It's be simplified:
List<Map<String, Object>> resp = HttpClient.of("https://api.mojang.com/user/profiles/" + N.guid()+ "/names").get(List.class);
List<String> names = resp.stream().map(m -> (String) (m.get("name"))).collect(Collectors.toList());

Creating JSON output in Java

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"]}}

need GSON to return a Java JSONArray

I'm not able to return a JSONArray, instead my object appears to be a String. the value of myArray is the same value as jsonString. The object is a String object and not a JSONArray. and both jsonString and myArray prnt:
[{"id":"100002930603211",
"name":"Aardvark Jingleheimer",
"picture":"shortenedExample.jpg" },
{"id":"537815695",
"name":"Aarn Mc",
"picture":"shortendExample.jpg" },
{"id":"658471072",
"name":"Adrna opescu",
"picture":"shortenedExample.jpg"
}]
How can I convert this to an actual Java JSONArray? thanks!
//arrPersons is an ArrayList
Gson gson = new Gson();
String jsonString = gson.toJson(arrPersons);
JsonParser parser = new JsonParser();
JsonElement myElement = parser.parse(jsonString);
JsonArray myArray = myElement.getAsJsonArray();
I think you can do what you want without writing out a json string and then re-reading it:
List<Person> arrPersons = new ArrayList<Person>();
// populate your list
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(arrPersons, new TypeToken<List<Person>>() {}.getType());
if (! element.isJsonArray()) {
// fail appropriately
throw new SomeException();
}
JsonArray jsonArray = element.getAsJsonArray();
public JSONArray getMessage(String response){
ArrayList<Person> arrPersons = new ArrayList<Person>();
try {
// obtain the response
JSONObject jsonResponse = new JSONObject(response);
// get the array
JSONArray persons=jsonResponse.optJSONArray("data");
// iterate over the array and retrieve single person instances
for(int i=0;i<persons.length();i++){
// get person object
JSONObject person=persons.getJSONObject(i);
// get picture url
String picture=person.optString("picture");
// get id
String id=person.optString("id");
// get name
String name=person.optString("name");
// construct the object and add it to the arraylist
Person p=new Person();
p.picture=picture;
p.id=id;
p.name=name;
arrPersons.add(p);
}
//sort Arraylist
Collections.sort(arrPersons, new PersonSortByName());
Gson gson = new Gson();
//gson.toJson(arrPersons);
String jsonString = gson.toJson(arrPersons);
sortedjsonArray = new JSONArray(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
return sortedjsonArray;
}
public class PersonSortByName implements Comparator<Person>{
public int compare(Person o1, Person o2) {
return o1.name.compareTo(o2.name);
}
}
public class Person{
public String picture;
public String id;
public String name;
}

Categories