I have a List which I need to convert into JSON Object using GSON. My JSON Object has JSON Array in it.
public class DataResponse {
private List<ClientResponse> apps;
// getters and setters
public static class ClientResponse {
private double mean;
private double deviation;
private int code;
private String pack;
private int version;
// getters and setters
}
}
Below is my code in which I need to convert my List to JSON Object which has JSON Array in it -
public void marshal(Object response) {
List<DataResponse.ClientResponse> clientResponse = ((DataResponse) response).getClientResponse();
// now how do I convert clientResponse list to JSON Object which has JSON Array in it using GSON?
// String jsonObject = ??
}
As of now, I only have two items in List - So I need my JSON Object like this -
{
"apps":[
{
"mean":1.2,
"deviation":1.3
"code":100,
"pack":"hello",
"version":1
},
{
"mean":1.5,
"deviation":1.1
"code":200,
"pack":"world",
"version":2
}
]
}
What is the best way to do this?
There is a sample from google gson documentation on how to actually convert the list to json string:
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> target = new LinkedList<String>();
target.add("blah");
Gson gson = new Gson();
String json = gson.toJson(target, listType);
List<String> target2 = gson.fromJson(json, listType);
You need to set the type of list in toJson method and pass the list object to convert it to json string or vice versa.
If response in your marshal method is a DataResponse, then that's what you should be serializing.
Gson gson = new Gson();
gson.toJson(response);
That will give you the JSON output you are looking for.
Assuming you also want to get json in format
{
"apps": [
{
"mean": 1.2,
"deviation": 1.3,
"code": 100,
"pack": "hello",
"version": 1
},
{
"mean": 1.5,
"deviation": 1.1,
"code": 200,
"pack": "world",
"version": 2
}
]
}
instead of
{"apps":[{"mean":1.2,"deviation":1.3,"code":100,"pack":"hello","version":1},{"mean":1.5,"deviation":1.1,"code":200,"pack":"world","version":2}]}
you can use pretty printing. To do so use
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(dataResponse);
Make sure to convert your collection to Array:
Gson().toJson(objectsList.toTypedArray(), Array<CustomObject>::class.java)
We can also use another workaround by first creating an array of myObject then convert them into list.
final Optional<List<MyObject>> sortInput = Optional.ofNullable(jsonArgument)
.map(jsonArgument -> GSON.toJson(jsonArgument, ArrayList.class))
.map(gson -> GSON.fromJson(gson, MyObject[].class))
.map(myObjectArray -> Arrays.asList(myObjectArray));
Benifits:
we are not using reflection here. :)
Related
I have a json reponse like given below.Basically,I want to convert an object and use it.
[
{
"Id": 1290,
"N": "Türkiye",
"Fid": 196,
"EC": 10,
"CL": null,
"SID": 0
},
{
"Id": 1239,
"N": "Dünya",
"Fid": 152,
"EC": 63,
"CL": null,
"SID": 0
}
]
... Goes on
Here is what I have tried,I am using org.json library.
String jsonString = response.body().string(); // Getting json response and converting to string.
JSONObject jsonResponse = new JSONObject( jsonString ); // Not working
JSONArray jsonArray = new JSONArray( jsonString ); // Not working
JSONArray matches = new JSONArray( jsonString ).getJSONArray(0); // Not working
But I am gettin those errors
A JSONObject text must begin with '{' at 0 [character 1 line 1]
A JSONArray text must begin with '{' at 0 [character 1 line 1]
I have checked topics like Parse JSON Array without Key. But the json described not like mine.
Any idea what should ı do?
in Java you would first need to define a class which has all the attributes
public class MyClass {
private int Id;
private int N;
private int Fid;
private int EC;
private int CL;
private int Sid;
// getters, setters, no arg constructor
}
then you can use for example gson library to parse it like this:
MyClass[] myClassArray = gson.fromJson(jsonString , MyClass[].class)
I really recommend you to use the Gson library it's way better to perform data operations:
public class User {
int id;
String n;
int fid;
int ec;
String cl;
int sid;
public static User[] parse(String s){
return new GsonBuilder().create().fromJson(s, User[].class);
}
}
Have you looked into Google's Gson? It is really easy to use and you can both serialize and deserialize objects.
Here is an example:
public Company[] deserializeCompany() {
Gson gson = new Gson();
Company[] companies = gson.fromJson(companiesJSON, Company[].class);
return companies;
}
First you need to make a template class that has a member field for each key in the json. E.g. private String id for the 'Id' key in the json you provided. In my example it is the Company class.
Next you make a new Gson object using Gson gson = new Gson(); and use the .fromJson function supplying it both the Json array and the Object array type (which is of the form MyClass[].class).
First, your question is not to convert a JSON array without key. Second, there are many popular JSON libraries can achieve what you want such as org.json, Jackson, Gson and so on.
Here comes several examples:
With org.json, you can retrieve field values in a JSON array as follows:
JSONArray jsonResponse = new JSONArray(jsonStr);
System.out.println(jsonResponse.get(0).toString());
System.out.println("Id: " + jsonResponse.getJSONObject(0).get("Id"));
System.out.println("N : " + jsonResponse.getJSONObject(0).get("N"));
And the expected output should be:
{"Fid":196,"CL":null,"Id":1290,"N":"Türkiye","EC":10,"SID":0}
Id: 1290
N : Türkiye
With Jackson, you can retrieve field values in a JSON array as follows:
ObjectMapper objectMapper = new ObjectMapper();
List<Map<String, Object>> jsonResponse = objectMapper.readValue(jsonStr, new TypeReference<List<Map<String, Object>>>() {});
System.out.println(jsonResponse.toString());
System.out.println("Id: " + jsonResponse.get(0).get("Id"));
System.out.println("N : " + jsonResponse.get(0).get("N"));
And the expected output should be:
{Id=1290, N=Türkiye, Fid=196, EC=10, CL=null, SID=0}
Id: 1290
N : Türkiye
3. Furthermore, if you define a POJO as follows:
class MyObject {
private #JsonProperty("Id") int id;
private #JsonProperty("N") String n;
private #JsonProperty("Fid") int fid;
private #JsonProperty("EC") int ec;
private #JsonProperty("CL") int cl;
private #JsonProperty("SID") int sid;
//general getters, setters and toString
}
Then you can deserialize the JSON response to your POJO by:
ObjectMapper objectMapper = new ObjectMapper();
List<MyObject> jsonResponse = objectMapper.readValue(jsonStr, new TypeReference<List<MyObject>>() {});
System.out.println(jsonResponse.get(0).toString());
System.out.println("Id: " + jsonResponse.get(0).getId());
System.out.println("N : " + jsonResponse.get(0).getN());
And the expected output should be:
MyObject{id=1290, n='Türkiye', fid=196, ec=10, cl=0, sid=0}
Id: 1290
N : Türkiye
I want to convert this Json String to an Array.
My hashmap named "HASHMRM"
this is my Json String:
[
{"id":1,"name":"hamid"},
{"id":2,"name":"mohamad"},
{"id":3,"name":"ali"},
{"id":4,"name":"john"},
{"id":5,"name":"smith"}
]
and I wanna to convert this Json String To an Array like this
String myJsonstring ="[{"id":1,"name":"hamid"},{"id":2,"name":"mohamad"},{"id":3,"name":"ali"},{"id":4,"name":"john"},{"id":5,"name":"smith"}]";
string[] AA = Jsons.....
int i =0;
while(i<string.lenght)
{
HASHMRM.put(AA[i].split()//First, AA[i].split()//second);
i++;
}
Use Gson.
First, you need POJO class that matches your data.
class MyUser {
int id;
String name;
}
Then, convert your string to List of POJO class.
// This is your string.
String myJsonString = "[{\"id\":1,\"name\":\"hamid\"},{\"id\":2,\"name\":\"mohamad\"},{\"id\":3,\"name\":\"ali\"},{\"id\":4,\"name\":\"john\"},{\"id\":5,\"name\":\"smith\"}]";
// Create new Gson object.
Gson gson = new Gson();
// Convert
List<MyUser> userList = gson.fromJson(myJsonString, new TypeToken<List<MyUser>>() {
}.getType());
Next, use it!
for (MyUser u : userList) {
HASHMRM.put(u.id, u.name);
}
Remember: Instead of using the HASHMRM as variable name, I suggest you to use java conventional camel case name HashMRM.
I have this JSON file called city.list.json, containing objects like these:
{
"id": 707860,
"name": "Hurzuf",
"country": "UA",
"coord": {
"lon": 34.283333,
"lat": 44.549999
}}
How can I put name's value into array?
This is the code I've tried:
String name = null;
JSONArray jsonArr = new JSONArray("[JSON String]");
ArrayList<Data> dataList = new ArrayList<>();
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
Data data = new Data();
data.name = jsonObj.getString("name");
dataList.add(data);
}
But it gives me errors on data saying "Constructor Data in class Data cannot applied to given types"
You can use GSON library to achieve this task:
String input = yourSampleJson;
Gson gson = new Gson();
Map<String,Object> inputPojo = new HashMap<>();
inputPojo = gson.fromJson(input, inputPojo.class); // This map now contains the representation of your JSON.
I generally prefer having a POJO class which represents your JSON structure something as :
Class DanielePojo {
Integer id;
String name;
String country;
Coord coord; // This is another class similar to this POJO which is represented as Object in your JSON
// Then your getters and setters
}
Then you can convert JSON into Pojo object directly without having a MAP as an intermediate object.
DanielePojo pojo = new GSON.fromJSON(input,DanielePojo.class);
I hava json in the following form:
"result":[
{"question":"3", "answer":"Doe"},
{"question":"5", "answer":"Smith"},
{"question":"8","answer":"Jones"}
]
and a Java class ->
public class UserResponses {
private Integer question;
private String answer;
//getters and setters
}
How can i parse the json into a List of UserResponses?
For example, with GSON?
JSONObject data = new JSONObject("your_json_data_here");
JSONArray questionArray = data.getJSONArray("result");
//Create an array of questions to store the data
UserResponse[] responsess = new UserResponse[questionArray.length()];
//Step through the array of JSONObjects and convert them to your Java class
Gson gson = new Gson();
for(int i = 0; i < questionArray.length(); i++){
responses[i] = gson.fromJson(
questionArray.getJSONObject(i).toString(), UserResponse.class);
}
This would be a simple way to parse the data with gson. If you wanted to do it without gson you would just have to use the getters and setters for your UserResponse class with questionArray.getJSONObject(i).getString("question") and questionArray.getJSONObject(i).getString("answer").
How can I parse the json into a List of UserResponses? For example, with GSON?
Given the "json" variable containing the json rappresenting a list of your_kind I would do as following (using reflection):
Type type = new TypeToken>() {}.getType();
List yourList = Gson().fromJSON(json, type);
I've recently decided to rewrite one of my older android applications and I can't figure out how to convert server response like this:
{
"response": "SUCCESS",
"data": {
"0": {
... fields ...
},
"1": {
... fields ...
},
... another objects
}
}
to regular java object (or in this case list of objects). I was previously using this method:
JSONObject response = new JSONObject(stringResponse);
JSONObject dataList = response.getJSONObject("data");
int i = 0;
while (true) {
dataList.getJSONObject(String.valueOf(i)); // here I get wanted object
i++;
}
to get relevant objects and then I can put them into List, but now I'm using Retrofit library and I'm not able to find any clean solution to parse such weird object using gson and retrofit.
Thanks for any help.
Edit: What I want:
Send request using retrofit like this:
#GET("/some params")
void restCall(... another params..., Callback<Response> callback);
and then have List of objects in Response object. What I don't know is how to declare Response object, so it can convert that weird response into normal List of objects.
You have many libraries around for this.. One i used was json-simple There you can just use:
JSONValue.parse(String);
look into gson too! i'm using it for all my projects, serializing and deserializing to pojos is remarkably simple and customizable (if needed, most things are fine out of the box)
gson
here is their first example:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
obj = gson.fromJson( json );
==> you get back the same object