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
If you have list for example list of like this
List<String> list = Arrays.asList("Kolkata","data can be, null",null,"05/31/2020",null);
list.replaceAll(t -> Objects.isNull(t) ? "''" : t);
System.out.println(list);
Here oputput will be:
[Kolkata, data can be, null, '', 05/31/2020, '']
Related
can anyone help me, i'am new on java programing
let say i have JSONArray with this data below :
[{
"STATUSUPDATE": 0,
"IDSERV": "2"
}, {
"STATUSUPDATE": 0,
"IDSERV": "3"
}, {
"STATUSUPDATE": 0,
"IDSERV": "1"
}]
How to update STATUSUPDATE to 1 in IDSERV 2
How to update STATUSUPDATE to 2 in IDSERV 3
and was trying to loop the data
for (int i=0; i < array.length; i++){
JSONObject itemArr = (JSONObject)array.get(j);
if(itemArr.get("IDSERV").equals(2)){
//should be itemArr.set(with new val)
//but method *set* can cal; only on JSONArray not an JSONObject
//and looping the next one
}
}
can anyone help me
JSONArray specific code:
Output
Initial array : [{"STATUSUPDATE":0,"IDSERV":"2"},{"STATUSUPDATE":0,"IDSERV":"3"},{"STATUSUPDATE":0,"IDSERV":"1"}]
Output array : [{"STATUSUPDATE":"1","IDSERV":"2"},{"STATUSUPDATE":"2","IDSERV":"3"},{"STATUSUPDATE":0,"IDSERV":"1"}]
Code
public class Test {
public static void main(String[] args) throws JSONException {
JSONArray array = new JSONArray("[{\"STATUSUPDATE\":0,\"IDSERV\":\"2\"},{\"STATUSUPDATE\":0,\"IDSERV\":\"3\"},{\"STATUSUPDATE\":0,\"IDSERV\":\"1\"}]");
System.out.println("Initial array : " + array);
for (int i=0; i < array.length(); i++){
JSONObject jsonObject = new JSONObject(array.get(i).toString());
if(jsonObject.get("IDSERV").equals("2")) {
jsonObject.put("STATUSUPDATE", "1");
array.put(i, jsonObject);
}
else if(jsonObject.get("IDSERV").equals("3")) {
jsonObject.put("STATUSUPDATE", "2");
array.put(i, jsonObject);
}
}
System.out.println("Output array : " + array);
}
}
Here is the code:
array is your JSONArray
for (int i=0; i < array.length(); i++){
JSONObject itemArr = (JSONObject)arr.get(i);
if(itemArr.get("IDSERV").getAsString().equals("2")){
itemArr.put("STATUSUPDATE", 1);
}else if(itemArr.get("IDSERV").getAsString().equals("3")){
itemArr.put("STATUSUPDATE", 2);
}
}
Now, if you print array then you can see values are changed.
Using regex and replaceAll:
String json = ...
json.replaceAll("(?<=\"IDSERV\":\")\\d*(?=\")", new value);
The above will locate and replace ALL IDSERV fields.
If you only want to find and replace ONE of the IDSERV fields, change the \\d to [] and put the expected value to swap in between the braces.
Ex: [1] will find and replace all values equal to 1.
EDIT1:
Ok, you just edited the question.
This regex allows you to target a specific IDSERV and changes its STATUSUPDATE field.
(?<=:)\d*(?=,"IDSERV":"1")
In the above, change the number 1 to whatever value of IDSERV you want to look for.
In java that would be:
String json = ...
json.replaceAll("(?<=:)\\d*(?=,\"IDSERV\":\"1\")", new value);
I used replacing some fields its decimal values to zero on user role. Its working
shimpment=shimpment.replaceAll("\"shipmentValue\":[0-9]+.[0-9]+", "\"shipmentValue\":0.00");
shimpment=shimpment.replaceAll("\"price\":[0-9]+.[0-9]+", "\"price\":0.00");
shimpment=shimpment.replaceAll("\"tax\":[0-9]+.[0-9]+", "\"tax\":0.00");
This is problematic JSON data that I'm trying to read:
"555":{
"ID":115,
"name":"John Smith",
"email":"john#gmail.com",
"tel":"0123456789"
},
"568":{
"ID":221,
"name":"Xxxx xxxxx",
"email":"xxxx#gmail.com",
"tel":"0123456789"
}}
I want to read id, name and email and separate them with "\t", but I don't know key value because it is generated via random function.
String data;
JSONObject json = new JSONObject(sb.toString()); / sb is StringBuffer
String[] keyValues = JSONObject.getNames(json);
for(int i=0; keyValues.length < i; i++) {
data = jsonObj.getString(keyValues[i]);
}
I encountered a few JSON Java examples here, but nothing like this. Can someone explain to me where I'm wrong?
JSON supports objects as children of objects. The getJSONObject() method is useful to retrieve those child objects
for(int i=0; keyValues.length < i; i++) {
JSONObject obj = jsonObj.getJSONObject(keyValues[i]);
System.out.println (obj.getInt("ID")+" "+obj.getString("name");
}
Reference: http://developer.android.com/reference/org/json/JSONObject.html#getJSONObject(java.lang.String)
In my android project, I have an activity in which I want to obtain data from database using a PHP script. I manage the result of the script in this line :
String result = EntityUtils.toString(entity);
I created the jsonObject :
JSONObject jsonObject = new JSONObject(result);
I print this line and get: {"id":"1"}{"id":"2"}{"id":"3"}
But when I do this:
int i;
for(i=0;i<array.length;i++)
{
array[i] = "ID : "+jsonObject.getString("id");
}
I obtain "id : 1" three times, so I think there are some errors in the cycle..
the code of script php is here :
#Get the first row of the results
while ($row = mysqli_fetch_row($data)) {
#Build the result array (Assign keys to the values)
$result_data = array(
'id' =>$row[0],
);
#Output the JSON data
echo json_encode($result_data);
change to:
int i;
for(i=0;i<array.length;i++)
{
jsonObject=array[i];
String s = "ID : "+jsonObject.getString("id");
}
{"id":"1"}{"id":"2"}{"id":"3"}
is no valid code for a single JSON object - see here: JSON syntax.
I can only guess what you try to achieve, but I would guess your intention is to have a JSON array with 3 objects, each having an "id" value. The JSON code for such a structure should look like this:
[{"id":"1"},{"id":"2"},{"id":"3"}]
If you can make "EntityUtils.toString(entity)" to return the above JSON code, the following loop should also work:
JSONArray ja = new JSONArray(result);
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject = ja.getJSONObject(i);
System.out.println("ID : "+jsonObject.getString("id"));
}
edit
On a side note: I believe you get the result you describe, because when you call
new JSONObject(result);
where the result is a String that consists of
{"id":"1"}{"id":"2"}{"id":"3"}
then most likely JSONObject stops parsing the JSON code after the first right brace without throwing a parse exception. So it actually only parses the first JSON object and because of this you get "id : 1" three times. Personally I would consider this behavior a bug, so consider reporting it.
Is there any way to convert a normal Java array or ArrayList to a Json Array in Android to pass the JSON object to a webservice?
If you want or need to work with a Java array then you can always use the java.util.Arrays utility classes' static asList() method to convert your array to a List.
Something along those lines should work.
String mStringArray[] = { "String1", "String2" };
JSONArray mJSONArray = new JSONArray(Arrays.asList(mStringArray));
Beware that code is written offhand so consider it pseudo-code.
ArrayList<String> list = new ArrayList<String>();
list.add("blah");
list.add("bleh");
JSONArray jsArray = new JSONArray(list);
This is only an example using a string arraylist
example key = "Name" value = "Xavier" and the value depends on number of array you pass in
try
{
JSONArray jArry=new JSONArray();
for (int i=0;i<3;i++)
{
JSONObject jObjd=new JSONObject();
jObjd.put("key", value);
jObjd.put("key", value);
jArry.put(jObjd);
}
Log.e("Test", jArry.toString());
}
catch(JSONException ex)
{
}
you need external library
json-lib-2.2.2-jdk15.jar
List mybeanList = new ArrayList();
mybeanList.add("S");
mybeanList.add("b");
JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);
Google Gson is the best library http://code.google.com/p/google-gson/
This is the correct syntax:
String arlist1 [] = { "value1`", "value2", "value3" };
JSONArray jsonArray1 = new JSONArray(arlist1);
For a simple java String Array you should try
String arr_str [] = { "value1`", "value2", "value3" };
JSONArray arr_strJson = new JSONArray(Arrays.asList(arr_str));
System.out.println(arr_strJson.toString());
If you have an Generic ArrayList of type String like ArrayList<String>. then you should try
ArrayList<String> obj_list = new ArrayList<>();
obj_list.add("value1");
obj_list.add("value2");
obj_list.add("value3");
JSONArray arr_strJson = new JSONArray(obj_list));
System.out.println(arr_strJson.toString());
My code to convert array to Json
Code
List<String>a = new ArrayList<String>();
a.add("so 1");
a.add("so 2");
a.add("so 3");
JSONArray jray = new JSONArray(a);
System.out.println(jray.toString());
output
["so 1","so 2","so 3"]
Convert ArrayList to JsonArray
: Like these [{"title":"value1"}, {"title":"value2"}]
Example below :
Model class having one param title and override toString method
class Model(
var title: String,
var id: Int = -1
){
override fun toString(): String {
return "{\"title\":\"$title\"}"
}
}
create List of model class and print toString
var list: ArrayList<Model>()
list.add("value1")
list.add("value2")
Log.d(TAG, list.toString())
and Here is your output
[{"title":"value1"}, {"title":"value2"}]
I'm using a simple php API (that I wrote) that returns a JSON formatted string such as:
[["Air Fortress","5639"],["Altered Beast","6091"],["American Gladiators","6024"],["Bases Loaded II: Second Season","5975"],["Battle Tank","5944"]]
I now have a String that contains the JSON formatted string but need to convert it into two String arrays, one for name and one for id. Are there any quick paths to accomplishing this?
You can use the org.json library to convert your json string to a JSONArray which you can then iterate over.
For example:
String jsonString = "[[\"Air Fortress\",\"5639\"],[\"Altered Beast\",\"6091\"],[\"American Gladiators\",\"6024\"],[\"Bases Loaded II: Second Season\",\"5975\"],[\"Battle Tank\",\"5944\"]]";
List<String> names = new ArrayList<String>();
List<String> ids = new ArrayList<String>();
JSONArray array = new JSONArray(jsonString);
for(int i = 0 ; i < array.length(); i++){
JSONArray subArray = (JSONArray)array.get(i);
String name = (String)subArray.get(0);
names.add(name);
String id = (String)subArray.get(1);
ids.add(id);
}
//to convert the lists to arrays
String[] nameArray = names.toArray(new String[0]);
String[] idArray = ids.toArray(new String[0]);
You can even use a regex to get the job done, although its much better to use a json library to parse json:
List<String> names = new ArrayList<String>();
List<String> ids = new ArrayList<String>();
Pattern p = Pattern.compile("\"(.*?)\",\"(.*?)\"") ;
Matcher m = p.matcher(s);
while(m.find()){
names.add(m.group(1));
ids.add(m.group(2));
}