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);
Related
I have a JSON object as follows:
{
"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9",
"user":{
"pk":17,
"username":"user1",
"email":"user1#gmail.com",
"first_name":"",
"last_name":""
}
}
I am trying to get two JSON object from it; token and user. I have tried two different ways but both are failing:
//response.body().string() is the above json object
JSONArray jsonArray = new JSONArray(response.body().string());
jsonObjectRoot = new JSONObject(response.body().string());
Could any one please let me know how I could split this to two JSON objects?
You can split it this way:
// source object
JSONObject sourceObject = new JSONObject(sourceJson);
String tokenKey = "token";
// create new object for token
JSONObject tokenObject = new JSONObject();
// transplant token to new object
tokenObject.append(tokenKey, sourceObject.remove(tokenKey));
// if append method does not exist use put
// tokenObject.put(tokenKey, sourceObject.remove(tokenKey));
System.out.println("Token object => " + tokenObject);
System.out.println("User object => " + sourceObject);
Above code prints:
Token object => {"token":["eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"]}
User object => {"user":{"last_name":"","pk":17,"first_name":"","email":"user1#gmail.com","username":"user1"}}
You can parse a json string with
var obj = JSON.parse(jsonString);
You can filter sub parts of a json object by simply addressing them
var token = obj.token;
var user = obj.user;
The safer / cleaner way to do it is to create a POJO and deserialize your JSON into it using Jackson. Your pojo:
public class MyObject {
String token;
User user;
static class User {
int pk;
String username;
String email;
String first_name;
String last_name;
}
}
Then, when you want to deserialize:
import com.fasterxml.jackson.databind.ObjectMapper;
and
ObjectMapper mapper = new ObjectMapper();
MyObject myObject = mapper.readValue(jsonString, MyObject.class);
String token = myObject.token;
User user = myObject.user;
...
I recently faced the same situation, I used the below code which worked for me:
JSONObject jo1 = new JSONObject(output);
JSONObject tokenObject = new JSONObject();
tokenObject.put("token", jo1.get("token"));
JSONObject userObject = new JSONObject();
userObject.put("user", jo1.get("user"));
Here I am creating a new empty JSONObject and then put the retrieved object from the original object in the newly created JSONObject.
You can also verify the output by just sysout:
System.out.println("token:" + tokenObject.get("token"));
System.out.println("user:" + userObject.get("user"));
Output in my case :
token::eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
user:{"last_name":"","pk":17,"first_name":"","email":"user1#gmail.com","username":"user1"}
Yep. It is a JSON string.
Using like this
JSONParser jparse=new JSONParser();
JSONObject jObj=(JSONObject)jParse.parse(jsonString);
jObj will contain json Object now.
I'm stuck parsing a nested JSON Array. This should be fairly simple but I can't seem to get it to work.
I have a JSON Array like below:
{"currentPage":0,
"totalPages":1,
"totalSize":1,
"first":true,
"last":true,
"list"[{"date":"2018-11-07T09:34:25.042+0000",
"lastUpdated":"2018-11-07T09:34:25.266+0000",
"id"130674,
"active":true,
"address":null,
"storeMobileNumbers":
[{"id":130676,"mobile":"+201008005090","version":0
}]
}]
}
I'm trying to get the address from the list first, then get the values from storeMobileNumbers.
I have a POJO class for the list, and now I have created a POJO class for the StoreMobileNumbers.
This is what I have right now:
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
Type collectionType = new TypeToken<List<MyStore>>(){}.getType();
Type collection2 = new TypeToken<List<StoreMobileNumber>>({}.getType();
JSONObject obj = new JSONObject(json);
if (obj.has("list")) {
String myList = obj.get("list").toString();
list1 = gson.fromJson(myList, collectionType);
JSONArray obj1 = new JSONArray(list1);
JSONObject numbersObject = obj1.toJSONObject(obj1);
String mobileList =
numbersObject.get("storeMobileNumbers").toString();
mobileNumbers = gson.fromJson(mobileList, collection2);
}
My StoreMobileNumbersClass:
public class StoreMobileNumber{
public Long id;
public String mobile;
}
So far, my efforts have been unsuccessful. I'm getting the following error:
org.json.JSONException: No value for storeMobileNumbers
Can someone help me see what I'm missing here?
Change to following -
String myList = obj.get("list").toString();
list1 = gson.fromJson(myList, collectionType); // delete this not required
JSONArray obj1 = new JSONArray(list1);
JSONObject numbersObject = obj1.getJsonObject(0); // change this to get first object from the JsonArray
String mobileList =
numbersObject.get("storeMobileNumbers").toString();
mobileNumbers = gson.fromJson(mobileList, collection2);
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 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 am using GSON library to send JSON response. I have a model which has a couple fields. Now my code is for sending JSON response is:
#RequestMapping(value="/sampleData/info", headers="Accept=*/*", method=RequestMethod.GET)
public #ResponseBody String getDealerInfoInJSON(#RequestParam("city") String city_id,
#RequestParam("dealer") String category_id) {
Gson gson = new Gson();
String s;
List<SampleData> foo = sampleDataService.getDealerInfo(city_id, category_id);
// foo contains [com.spring.model.SampleData#e64a0b]
List<SampleData> list = Collections.synchronizedList(
new Arraylist<SampleData>());
Iterator<SampleData> iterator = foo.iterator();
while (iterator.hasNext()) {
// Here I want to add sample data obj in list which is not working but
// new SampleData is working fine like added below:
list.add(iterator.next()) // Not working (stack overflow error)
list.add(new SampleData()); // Working
}
s = gson.toJson(list, ArrayList.class);
System.out.println(s); // This print [{}]
return s; // Works fine with a single object but not a list of objects
}
I don't know how to return JSON response of sample data objects fields. Please guide me.
You need to add property values in the sample data, otherwise you will get blank data [{}] as you are getting.
SampleData sample= new SampleData();
sample.setXXX(); // your setter methods to set data in object.
sample.setYYY();
sample.setCategory(category);
Gson gson = new Gson();
return gson.toJson(sample);