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);
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 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);
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 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.
I am trying to convert ArrayList of custom class to JsonArray. Below is my code. It executes fine but some JsonArray elements come as zeros even though they are numbers in the ArrayList. I have tried to print them out. Like customerOne age in the ArrayList is 35 but it is 0 in the JsonArray. What could be wrong?
ArrayList<Customer> customerList = CustomerDB.selectAll();
Gson gson = new Gson();
JsonElement element =
gson.toJsonTree(customerList , new TypeToken<List<Customer>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
Below code should work for your case.
List<Customer> customerList = CustomerDB.selectAll();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(customerList, new TypeToken<List<Customer>>() {}.getType());
if (! element.isJsonArray() ) {
// fail appropriately
throw new SomeException();
}
JsonArray jsonArray = element.getAsJsonArray();
Heck, use List interface to collect values before converting it JSON Tree.
As an additional answer, it can also be made shorter.
List<Customer> customerList = CustomerDB.selectAll();
JsonArray result = (JsonArray) new Gson().toJsonTree(customerList,
new TypeToken<List<Customer>>() {
}.getType());
Don't know how well this solution performs compared to the other answers but this is another way of doing it, which is quite clean and should be enough for most cases.
ArrayList<Customer> customerList = CustomerDB.selectAll();
Gson gson = new Gson();
String data = gson.toJson(customerList);
JsonArray jsonArray = new JsonParser().parse(data).getAsJsonArray();
Would love to hear from someone else though if, and then how, inefficient this actually is.
Consider a list of Objects of type Model.class
ArrayList<Model> listOfObjects = new ArrayList<Model>();
List to JSON
String jsonText = new Gson().toJson(listOfObjects);
JSON to LIST
Type listType = new TypeToken<List<Model>>() {}.getType();
List<Model> myModelList = new Gson().fromJson(jsonText , listType);
For Anyone who is doing it in Kotlin, you can get it this way,
val gsonHandler = Gson()
val element: JsonElement = gsonHandler.toJsonTree(yourListOfObjects, object : TypeToken<List<YourModelClass>>() {}.type)
List<> is a normal java object, and can be successfully transformed using standard gson object api.
List in gson looks like this:
"libraries": [
{
//Containing object
},
{
//Containing object
}
],
...
Use google gson jar, Please see sample code below,
public class Metric {
private int id;
...
setter for id
....
getter for id
}
Metric metric = new Metric();
metric.setId(1);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.serializeNulls();
Gson gson = gsonBuilder.create();
System.out.println(gson.toJson(metric));
StringBuffer jsonBuffer = new StringBuffer("{ \"rows\": [");
List<Metric> metrices = new ArrayList<Metric>();
// assume you have more elements in above arraylist
boolean first = true;
for (Metric metric : metrices) {
if (first)
first = false;
else
jsonBuffer.append(",");
jsonBuffer.append(getJsonFromMetric(metric));
}
jsonBuffer.append("]}");
private String getJsonFromMetric(Metric metric) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.serializeNulls();
Gson gson = gsonBuilder.create();
return gson.toJson(metric);
}