null replace into string in hiberante - java

I have below string output :
["Kolkata","data can be, null",null,"05/31/2020",null]
but I want to have the output like below format in Java
["Kolkata","data can be, null","","05/31/2020",""]
please help me .
I am converting object to json data . Please see the below codes
List<String> test = new ArrayList<>();
List<Object[]> data =query.list();
for (int i = 0; i < data.size(); i++) {
Object[] row = (Object[]) data.get(i);
String jsonString = gson.toJson(row);
test.add(jsonString);
}
I want to apply this on jsonString variable using java 7 as not using java 8

Gson doesn't allow you to change the serialized form of strings.
Probably better to change your objects -> replace null by empty string before serialization.

You can replace every null value with an empty string inside the array using another for loop. Here is an example that will do the same.
Object[] row = new Object[]{"Kolkata","data can be, null",null,"05/31/2020",null};
for (int i = 0; i < row.length; i++) {
if (row[i] == null) {
row[i] = "";
}
}

Related

JSON array parsing with Java [duplicate]

I am building an android app that needs to download and synchronise with an online database, I am sending my query from the app to a php page which returns the relevant rows from a database in JSON format.
can someone please tell me the best way to iterate through a JSON array?
I receive an array of objects:
[{json object},{json object},{json object}]
What is the simplest piece of code I could use to access the JSONObjects in the array?
EDIT: now that I think of it the method I used to iterate the loop was:
for (String row: json){
id = row.getInt("id");
name = row.getString("name");
password = row.getString("password");
}
So I guess I had was somehow able to turn the returned Json into and iterable array. Any Ideas how I could achieve this?
I apologise for my vaguness but I had this working from an example I found on the web and have since been unable to find it.
I think this code is short and clear:
int id;
String name;
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
Is that what you were looking for?
I have done it two different ways,
1.) make a Map
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i=0; i<settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
2.) make a JSONArray of names
JSONArray names = json.names();
JSONArray values = json.toJSONArray(names);
for(int i=0; i<values.length(); i++){
if (names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if (names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if (names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if (names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}
Unfortunately , JSONArray doesn't support foreach statements, like:
for(JSONObject someObj : someJsonArray) {
// do something about someObj
....
....
}
When I tried #vipw's suggestion, I was faced with this exception:
The method getJSONObject(int) is undefined for the type JSONArray
This worked for me instead:
int myJsonArraySize = myJsonArray.size();
for (int i = 0; i < myJsonArraySize; i++) {
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
// Do whatever you have to do to myJsonObject...
}
If you're using the JSON.org Java implementation, which is open source, you can just make JSONArray implement the Iterable interface and add the following method to the class:
#Override
public Iterator iterator() {
return this.myArrayList.iterator();
}
This will make all instances of JSONArray iterable, meaning that the for (Object foo : bar) syntax will now work with it (note that foo has to be an Object, because JSONArrays do not have a declared type). All this works because the JSONArray class is backed by a simple ArrayList, which is already iterable. I imagine that other open source implementations would be just as easy to change.
On Arrays, look for:
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
You are using the same Cast object for every entry.
On each iteration you just changed the same object instead creating a new one.
This code should fix it:
JSONArray jCastArr = jObj.getJSONArray("abridged_cast");
ArrayList<Cast> castList= new ArrayList<Cast>();
for (int i=0; i < jCastArr.length(); i++) {
Cast person = new Cast(); // create a new object here
JSONObject jpersonObj = jCastArr.getJSONObject(i);
person.castId = (String) jpersonObj.getString("id");
person.castFullName = (String) jpersonObj.getString("name");
castList.add(person);
}
details.castList = castList;
While iterating over a JSON array (org.json.JSONArray, built into Android), watch out for null objects; for example, you may get "null" instead of a null string.
A check may look like:
s[i] = array.isNull(i) ? null : array.getString(i);

Dynamically initialise array name

I am trying to create an array of objects with a MAX_N 6 object into this array, then create another array within an else statement to fit the rest of the array objects.
I would like to name the new array
sbag1
sbag2
etc
here is my code:
public static ShoppingBag[] packIntoBags(GroceryItem[] goods) {
ShoppingBag newBag = new ShoppingBag();
GroceryItem tmpObject = null;
int index = 0;
String bag = "newBag";
String bagNum = bag + index;
for (int i = 0; i < MAXNBAG; i++)
if (newBag.numItems() < MAX_NUM_ITEMS) {
for (int k = 0; i < MAX_NUM_ITEMS; i++) {
tmpObject = goods[i];
newBag.addToBag(tmpObject);
}
}
else {
ShoppingBag newBag1 = new ShoppingBag();
}
}
You will not be able to dynamically create new variables in java.
When I look at the signature of your method you don't need to return multiple variables, only an array of ShoppingBags.
You should create a variable of type List<ShoppingBag>:
List<ShoppingBag> shoppingsBags=new ArrayList<>();
each time you need a new ShoppingBag:
bag=new ShoppingBag();
shoppingBags.add(bag);
at the end convert this list to an array:
return shoppingBags.toArray(new ShoppingBag[0]);
Java is a statically compiled language. In general, it is not possible, or to be precise: not helpful to use "dynamic" names for variables.
What you could do instead: use a Map, or even more simple: an array of arrays to hold your data.

JSON : Array & Compare

I have a set of JSON array :
listSession: [h0y78u93, h0y78u93, h0y78u93, h0y78u93, h0y78u93, 9i88u93, 9i88u93, 9i88u93, 9i88u93, 9i88u93]
I've created the array using the below code:
ArrayList<String> listSession = new ArrayList<String>();
for(int u=1; u < k+1; u++) {
String str = Integer.toString(u);
JSONArray arrTime=(JSONArray)mergedJSON2.get(str);
JSONObject objSession;
StringsessionName;
for (Object ro : arrTime) {
objSession = (JSONObject) ro;
sessionName = String.valueOf(objSession.get("sessionID"));
listSession.add(sessionName);
}
}
May I get your advice or opinion on how am I going to compare the value from each of the attributes in the list. If it is the same, I should it as ONE.
Meaning from the above sample, the count should be only TWO instead of TEN.
Thank You.
You can utilize Arraylist.contains() method like below:
ArrayList<String> listSession = new ArrayList<String>();
for(int u=1; u < k+1; u++) {
String str = Integer.toString(u);
JSONArray arrTime=(JSONArray)mergedJSON2.get(str);
JSONObject objSession;
StringsessionName;
for (Object ro : arrTime) {
objSession = (JSONObject) ro;
sessionName = String.valueOf(objSession.get("sessionID"));
if (!listSession.contains(sessionName)) {
listSession.add(sessionName);
}
}
}
OR
You can use a Set implementation which doesn't allow duplicate values instead of ArrayList. There's no need to compare explicitly.
// initialize
Set sessionsSet = new HashSet();
//add like below
sessionsSet.add(sessionName);
sessionsSet.size() // getting the length which should be what you expect to be 2
I would recommend to use a Set over ArrayList here. You can use ArrayList and check the list whether it contains the element and add it. ArrayList.contains() takes O(n) time because it maintains a dynamic array inside. Where as a HashSet or TreeSet can do that check in O(1) and you also don't have to do that compare yourself.
Set<String> setSession = new HashSet<String>();
for(int u=1; u < k+1; u++) {
String str = Integer.toString(u);
JSONArray arrTime=(JSONArray)mergedJSON2.get(str);
JSONObject objSession;
StringsessionName;
for (Object ro : arrTime) {
objSession = (JSONObject) ro;
sessionName = String.valueOf(objSession.get("sessionID"));
setSession.add(sessionName);
}
}
If you're okay using Java 8, then you can use shorthand implementation like this:
Example:
ArrayList<String> data = new ArrayList<String>(Arrays.asList("A", "A", "A", "B", "B", "B"));
// This will be required if your target SDK < Android N
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
List<String> uniqueData = data.stream().distinct().collect(Collectors.toList()); // Results ["A", "B"]
}

how to iterate the json objects in the jsonarray [duplicate]

I am building an android app that needs to download and synchronise with an online database, I am sending my query from the app to a php page which returns the relevant rows from a database in JSON format.
can someone please tell me the best way to iterate through a JSON array?
I receive an array of objects:
[{json object},{json object},{json object}]
What is the simplest piece of code I could use to access the JSONObjects in the array?
EDIT: now that I think of it the method I used to iterate the loop was:
for (String row: json){
id = row.getInt("id");
name = row.getString("name");
password = row.getString("password");
}
So I guess I had was somehow able to turn the returned Json into and iterable array. Any Ideas how I could achieve this?
I apologise for my vaguness but I had this working from an example I found on the web and have since been unable to find it.
I think this code is short and clear:
int id;
String name;
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
Is that what you were looking for?
I have done it two different ways,
1.) make a Map
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i=0; i<settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
2.) make a JSONArray of names
JSONArray names = json.names();
JSONArray values = json.toJSONArray(names);
for(int i=0; i<values.length(); i++){
if (names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if (names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if (names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if (names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}
Unfortunately , JSONArray doesn't support foreach statements, like:
for(JSONObject someObj : someJsonArray) {
// do something about someObj
....
....
}
When I tried #vipw's suggestion, I was faced with this exception:
The method getJSONObject(int) is undefined for the type JSONArray
This worked for me instead:
int myJsonArraySize = myJsonArray.size();
for (int i = 0; i < myJsonArraySize; i++) {
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
// Do whatever you have to do to myJsonObject...
}
If you're using the JSON.org Java implementation, which is open source, you can just make JSONArray implement the Iterable interface and add the following method to the class:
#Override
public Iterator iterator() {
return this.myArrayList.iterator();
}
This will make all instances of JSONArray iterable, meaning that the for (Object foo : bar) syntax will now work with it (note that foo has to be an Object, because JSONArrays do not have a declared type). All this works because the JSONArray class is backed by a simple ArrayList, which is already iterable. I imagine that other open source implementations would be just as easy to change.
On Arrays, look for:
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
You are using the same Cast object for every entry.
On each iteration you just changed the same object instead creating a new one.
This code should fix it:
JSONArray jCastArr = jObj.getJSONArray("abridged_cast");
ArrayList<Cast> castList= new ArrayList<Cast>();
for (int i=0; i < jCastArr.length(); i++) {
Cast person = new Cast(); // create a new object here
JSONObject jpersonObj = jCastArr.getJSONObject(i);
person.castId = (String) jpersonObj.getString("id");
person.castFullName = (String) jpersonObj.getString("name");
castList.add(person);
}
details.castList = castList;
While iterating over a JSON array (org.json.JSONArray, built into Android), watch out for null objects; for example, you may get "null" instead of a null string.
A check may look like:
s[i] = array.isNull(i) ? null : array.getString(i);

java string replace all

I have a two dimensional array that contains pairs of strings. If one string is found it should replace it with its pair.
The code:
for (int i = 0; i < pairs.length; i++) {
if (name.contains(pairs[i][0])) {
name.replaceAll(pairs[i][0], abbr[i][1]);
}
}
It is not replacing the strings. What is the error?
You are neglecting to assign the result of replaceAll, and so the modification is lost.
Perhaps you want to keep the modified string as name:
for (int i = 0; i < pairs.length; i++) {
if (name.contains(pairs[i][0])) {
name = name.replaceAll(pairs[i][0], abbr[i][1]);
}
}
Note that java String objects are immutable, so calling name.replaceAll doesn't modify name, it returns a new String with the modifications.
String is immutable.
name.replaceAll(pairs[i][0], abbr[i][1]);
creates a new String (it doesn't modify the "name" String)
Try
name = name.replaceAll(pairs[i][0], abbr[i][1]);
A modified version of the string is being created, however it's return value is being lost.
name = name.replaceAll(pairs[i][0], abbr[i][1]);
should work.

Categories

Resources