I have this as a substring. It is a JSON string. I am trying to get the id string from it. I was able to do this by using two indexOf's and then substring the two indexOf's. What is a better solution.
Here is my string
"{"id":"762c094a-4b65-499e-b5b2-de34ef8d726e","createdTimestamp":1605558195131,"username":"sssdv","enabled":false,"totp":false,"emailVerified":false,"firstName":"cdf","lastName":"dddz","email":"hgddf#fdaddf.com","disableableCredentialTypes":[],"requiredActions":[],"notBefore":0,"access":{"manageGroupMembership":true,"view":true,"mapRoles":true,"impersonate":true,"manage":true}}"
And here is my code.
int id = results.indexOf("id");
int cr = results.indexOf("createdTimestamp");
String strId = results.substring(id + 5, cr - 3);
A better solution is to use an actual JSON parser. There are plenty out there. Take a look at this answer on a different question. I would suggest using Gson:
String json = "{\"id\":\"762c094a-4b65-499e-b5b2-de34ef8d726e\",\"createdTimestamp\":1605558195131,\"username\":\"sssdv\",\"enabled\":false,\"totp\":false,\"emailVerified\":false,\"firstName\":\"cdf\",\"lastName\":\"dddz\",\"email\":\"hgddf#fdaddf.com\",\"disableableCredentialTypes\":[],\"requiredActions\":[],\"notBefore\":0,\"access\":{\"manageGroupMembership\":true,\"view\":true,\"mapRoles\":true,\"impersonate\":true,\"manage\":true}}";
Gson gson = new GsonBuilder().setPrettyPrinting().create(); // Create the Gson instance
JsonElement element = gson.fromJson(json, JsonElement.class); // Parse it
String id = element.getAsJsonObject().get("id").getAsString(); // Get your desired element
System.out.println(id);
An even better solution would be to create a class with the fields from your JSON and parse the JSON string to that class:
public class MyObject {
// The names and types of these fields must match the ones in your JSON string
private String id, username, firstName, lastName, email;
private long createdTimestamp;
private boolean enabled, totp, emailVerified;
private String[] disableableCredentialTypes, requiredActions;
private int notBefore;
private Access access;
public String getId() {
return id;
}
// Other getters and setters...
private static class Access {
private boolean manageGroupMembership, view, mapRoles, impersonate, manage;
// ...
}
public static void main(String[] args) throws IOException {
String json = "{\"id\":\"762c094a-4b65-499e-b5b2-de34ef8d726e\",\"createdTimestamp\":1605558195131,\"username\":\"sssdv\",\"enabled\":false,\"totp\":false,\"emailVerified\":false,\"firstName\":\"cdf\",\"lastName\":\"dddz\",\"email\":\"hgddf#fdaddf.com\",\"disableableCredentialTypes\":[],\"requiredActions\":[],\"notBefore\":0,\"access\":{\"manageGroupMembership\":true,\"view\":true,\"mapRoles\":true,\"impersonate\":true,\"manage\":true}}";
Gson gson = new GsonBuilder().setPrettyPrinting().create(); // Create the Gson instance
MyObject object = gson.fromJson(json, MyObject.class); // Parse the string to your data type
System.out.println(object.getId()); // Print the id
}
}
String results = "{\"id\":\"762c094a-4b65-499e-b5b2-de34ef8d726e\",\"createdTimestamp\":1605558195131,\"username\":\"sssdv\",\"enabled\":false,\"totp\":false,\"emailVerified\":false,\"firstName\":\"cdf\",\"lastName\":\"dddz\",\"email\":\"hgddf#fdaddf.com\",\"disableableCredentialTypes\":[],\"requiredActions\":[],\"notBefore\":0,\"access\":{\"manageGroupMembership\":true,\"view\":true,\"mapRoles\":true,\"impersonate\":true,\"manage\":true}}";
String[] parts = results.split("\"");
System.out.println(parts[3]); //gives the id, every time
I have some codes that fetch some data from my API. My question is how can I list all the objects that I fetched before without using this jsonData.get(0), I expect something like jsonData.get(i), so I assume using something like below, but I can't use it, so how can I do that? Thanks.
for (int i=0;i<jsonData.length();i++){
MainActivity.java
List<Promo> jsonData = response.body();
Log.i("TESTER",""+jsonData);
String promoID = jsonData.get(0).getId_promo();
String promoTipe = jsonData.get(0).getPromo_type();
String promoValue = jsonData.get(0).getValue_based();
String promoName = jsonData.get(0).getPromo_name();
With POJO class that looks like this
Promo.java
public class Promo {
#SerializedName("id_promo")
private String id_promo;
#SerializedName("promo_name")
private String promo_name;
#SerializedName("promo_type")
private String promo_type;
#SerializedName("value_based")
private String value_based;
#SerializedName("quota")
private String quota;
#SerializedName("id_event")
private String id_event;
#SerializedName("description")
private String description;
public String getId_promo() {
return id_promo;
}
public void setId_promo(String id_promo) {
this.id_promo = id_promo;
}
public String getPromo_name() {
return promo_name;
}
}
ApiUrl.java
#FormUrlEncoded
#POST("promopublic")
Call<List<Promo>> getPromo(
#Field("id_event") String id_event,
#Field("total_buyer") String totalBuyer,
#Field("id_user") String id_user,
#Field("id_ticket") String id_ticket);
Using for loop like below solved my problem
for (int i=0;i<jsonData.size();i++){}
For a college assignment I need to create an app that retrieves product data from the API of a well known Dutch online store. I need to store the title, summary, price and image URLs of each product into a new Product object. These Products are stored into an ArrayList and the ArrayList is then returned.
Each product within the products array has a nested array called "images", which contains 6 product images. These images need to stored into my Product object's HashMap attribute, with the image size as key and the URL as value. However, I can't seem to get it right.
JSON data with the query "pokemon": https://api.bol.com/catalog/v4/search/?apikey=25C4742A92BF468EB2BD888FC8FBFF40&format=json&q=pokemon
Product class:
package com.example.bolcombrowser.domain;
import java.util.Map;
public class Product {
// Attributes
private String mTitle;
private String mSummary;
private double mPrice;
private Map < String, String > mImageUrls;
// Constructor
public Product(String mTitle, String mSummary, double mPrice, Map < String, String > mImageUrls) {
this.mTitle = mTitle;
this.mSummary = mSummary;
this.mPrice = mPrice;
this.mImageUrls = mImageUrls;
}
// Getters and Setters
public String getmTitle() {
return mTitle;
}
public void setmTitle(String mTitle) {
this.mTitle = mTitle;
}
public String getmSummary() {
return mSummary;
}
public void setmSummary(String mSummary) {
this.mSummary = mSummary;
}
public double getmPrice() {
return mPrice;
}
public void setmPrice(double mPrice) {
this.mPrice = mPrice;
}
public Map < String, String > getImageUrls() {
return mImageUrls;
}
public void setImageUrls(Map < String, String > imageUrls) {
this.mImageUrls = imageUrls;
}
}
parseJson method:
public static ArrayList < Product > parseJson(String productJsonStr) throws JSONException {
/* JSON array names. */
final String BOL_PRODUCTS = "products";
final String BOL_IMAGES = "images";
final String BOL_OFFERS = "offers";
/* JSON key names. */
final String BOL_TITLE = "title";
final String BOL_SUMMARY = "summary";
final String BOL_OFFERDATA = "offerData";
final String BOL_PRICE = "price";
final String BOL_KEY = "key";
final String BOL_URL = "url";
/* Variables to store product data into, and is then used to create new Product objects. */
String title;
String summary;
double price;
Map < String, String > imageUrls = new HashMap < > ();
/* ArrayList to store products into. */
ArrayList < Product > productList = new ArrayList < > ();
JSONObject productsJson = new JSONObject(productJsonStr);
JSONArray productsArray = productsJson.getJSONArray(BOL_PRODUCTS);
for (int i = 0; i < productsArray.length(); i++) {
JSONObject product = productsArray.getJSONObject(i);
/* Retrieve the title and summary of each product. */
title = product.getString(BOL_TITLE);
summary = product.getString(BOL_SUMMARY);
JSONArray imagesArray = product.getJSONArray(BOL_IMAGES);
for (int j = 0; j < imagesArray.length(); j++) {
JSONObject image = imagesArray.getJSONObject(j);
/* Retrieve each product's image sizes and URLs and store them into a HashMap. */
String imageSize = image.getString(BOL_KEY);
String imageUrl = image.getString(BOL_URL);
imageUrls.put(imageSize, imageUrl);
}
JSONObject offerData = product.getJSONObject(BOL_OFFERDATA);
JSONArray offers = offerData.getJSONArray(BOL_OFFERS);
JSONObject offer = offers.getJSONObject(0);
price = offer.getDouble(BOL_PRICE);
productList.add(new Product(title, summary, price, imageUrls));
}
return productList;
}
onPostExecute method:
#Override
protected void onPostExecute(String productData) {
if (productData != null) {
ArrayList < Product > productList;
try {
productList = JsonUtils.parseJson(productData);
for (Product product: productList) {
String title = product.getmTitle();
String summary = product.getmSummary();
double price = product.getmPrice();
String hashMap = product.getImageUrls().toString();
mTextViewOutput.append(title + "\n\n" + summary + "\n\n" + price + "\n\n" +
hashMap + "\n\n\n\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
When I test out my app, it seems to have stored the image URLs of the last product into every product's HashMap:
I've been staring at my code for hours and I can't seem to find out why it does this. I'm probably making a very silly mistake but I just can't seem to figure out what it is exactly.
Your Map<String, String> imageUrls = new HashMap<>(); is in the wrong place. It should be inside your first for loop, otherwise you are using the same Map for all your products.
...
for (int i = 0; i < productsArray.length(); i++) {
Map<String, String> imageUrls = new HashMap<>();
...
By the way, I suggest using gson library. It will make your code less boilerplate
I'm having a possible solution to the problem in my head but I don't quite know how to do that with code. I got stuck with invoking a method in a method in Java.
I have this code:
public Student getStudent(String queryWord){
//the queryWord here should actually be the String result that returnQueryColumn returns
}
private static Map<String, String> returnMap(String myQuery){
String[] params = myQuery.split("=");
Map<String, String> myMap = new HashMap<String, String>();
String myKey = params[0];
String myValue = params[1];
//myKey should be for example firstName, myValue should be the ACTUAL first name of the student
myMap.put(myKey,myValue);
return myMap;
}
private static String returnQueryColumn(Map<String, String> myMap){
//here I want to get just the KEY from the myMap(from the returnMap method)
//that key should be the column in my database, so I need this so that later on I can compare if the given key (firstName) is present in the database as a column
String queryWord = returnMap().get(); //query should get firstName in my case
return queryWord;
}
I know this code doesn't work, but I need some help, how can I achieve what I have in mind? I'm stuck at this - how can I invoke a method in other method, and make the string that is being returned in the first method to be a parameter in the second one.
Let's say you have Student class:
public class Student {
String fullName;
public Student(String fullName) {
this.fullName = fullName;
}
}
And, if I understood your intentions right, Main class can look like this.
Sample code prints student fullName property.
public class Main {
public static void main(String[] args) {
Student student = getStudent("john=John Appleseed");
System.out.println(student.fullName);
}
public static Student getStudent(String myQuery) {
return returnQueryColumn(myQuery);
}
private static Map<String, Student> returnMap(String myQuery){
String[] params = myQuery.split("=");
Map<String, Student> myMap = new HashMap<String, Student>();
String myKey = params[0];
String myValue = params[1];
Student student = new Student(myValue);
myMap.put(myKey, student);
return myMap;
}
private static Student returnQueryColumn(String myQuery) {
String[] params = myQuery.split("=");
String key = params[0];
return returnMap(myQuery).get(key);
}
}
I have singleton implementation of enum as below :
public enum DeviceDetail{
INSTANCE;
private Context context = null;
private int handlercheck = 0;
private String network = "";
private String deviceInfo = "NoData";
private String androidVersion = "";
private String appVersion = "";
private String appName = "";
private String deviceID;
private String deviceinfo;
public void initilize(){
// deviceInfo = getDeviceInfo();
networktype = getNetworktype(context);
deviceID = getDeviceID(context);
//androidVersion = getAndroidVersion();
appVersion = getAppVersion(context);
appName = getAppName(context);
}
DeviceDetail(){
deviceInfo = getDeviceInfo();
androidVersion = getAndroidVersion();
initilize();
}
public static DeviceDetail getInstance() {
return DeviceDetail.INSTANCE;
}
}
I want to convert this DeviceDetail to JSON using GSON, for that I have written
public static String convertObjectToJsonString(DeviceDetail deviceData) {
Gson gson = new Gson();
return gson.toJson(deviceData);
}
I am calling this method as
convertObjectToJsonString(DeviceDetail.INSTANCE)
but it only returns me the string "INSTANCE" not key value pairs as it does for objects. Suggest the changes need to be made so that I get string with all fields in enum in key value JSON.
I have ended up in using a not so elegant workaround as below :
public static String convertObjectToJsonString(DeviceDetail deviceData) {
// Gson gson = new Gson();
// GsonBuilder gb = new GsonBuilder();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("androidVersion", deviceData.getAndroidVersion());
jsonObject.addProperty("appName", deviceData.getAppName());
jsonObject.addProperty("appVersion", deviceData.getAppVersion());
jsonObject.addProperty("networkType", deviceData.getNetworktype());
jsonObject.addProperty("deviceInfo", deviceData.getDeviceInfo());
jsonObject.addProperty("deviceID", deviceData.getDeviceID());
jsonObject.addProperty("city", deviceData.getCity());
jsonObject.addProperty("country", deviceData.getCountry());
//jsonObject.addProperty("appName",deviceData.getAppName());
return jsonObject.toString();
}