Parse this json to java - java

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

Related

How to Convert a Multiple Array to Json Array and add Jsons to a hashmap

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.

Java - How can i read json file and put values into array

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

Convertig Json to List

I am trying to read and write a Json object to my database and I'm not getting how to convert the string you get from the database to a string and how I can use it later tp write back the changed list into my database again.
So when I'm asking the database for the field I want, I get this string back:
["[\"pw1\",\"pw2\",\"pw3\"]"]
Then I go and create an object of my class LastPasswords
List<String> passwordList = (List<String>) controllerServlet.getMacroDatabaseManager().executeNativeQuery(queryGet);
LastPasswords lastPasswords = new LastPasswords(passwordList);
Gson gson = new Gson();
String Json = gson.toJson(lastPasswords);
Here is the LastPasswords class
public class LastPasswords {
private List<String> passwords;
public LastPasswords(List<String> passwords) {
this.passwords = passwords;
}
public List<String> getPasswords(){
return passwords;
}
public void setPasswords(List<String> passwords){
this.passwords = passwords;
}
}
Then when I have this json string I try to get it as a list but I don't get the list.
lastPasswords.setPasswords((List<String>) gson.fromJson(banana, LastPasswords.class));
passwordList = lastPasswords.getPasswords();
Thanks for helping.
You can use com.google.gson.reflect.TypeToken.TypeToken to define return type of fromJson method.
Then, àter you have the list, you can create a new LastPasswords to use.
String json = "[\"pw1\",\"pw2\",\"pw3\"]";
Gson gson = new Gson();
List<String> list = gson.fromJson(json, new TypeToken<List<String>>() {}.getType());
System.out.println(list.size());
System.out.println(list);
Output:
3
[pw1, pw2, pw3]
You may use TypeToken to load the json string into a custom object.
String json = "[\"pw1\",\"pw2\",\"pw3\"]";
List<String> list = gson.fromJson(json, new TypeToken<List<String>>(){}.getType());
Or for an list of list of String
String json = "[\"[\"pw1\",\"pw2\",\"pw3\"]\"]";
List<List<String>> list = gson.fromJson(json, new TypeToken<List<List<String>>>(){}.getType());
list.get(0).get(0) == "pw1"
I would like to recommend to keep a Password class instead of keeping a ListPassword class.
Let us assume, you've a Password class like this.
public class Password {
public String password;
// Getter and setter
}
Now when you read the json string using gson, you might have to do this.
Password[] passwordArray = gson.fromJson(json, Password[].class);
This will map the json string into an array of Password. Then you might consider populating them in a list if you like.
List<Password> passwordList = Arrays.asList(passwordArray);

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 List to a JSON Object using GSON?

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. :)

Categories

Resources