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));
}
Related
I am getting json response in array form like this
["Monday","Wednesday","Friday"]
, but it is not saving as a array in android, I am storing that in a string like this
String daysOfInterest = map.get("daysOfinterest");
[{"careTypeId":"10","careTypeName":"Vacation Care","daysOfinterest":["Tuesday","Thursday","Saturday"],"childDaysOfInterestId":"424"},
{"careTypeId":"10","careTypeName":"Vacation Care","daysOfinterest":["Monday","Wednesday","Friday"],"childDaysOfInterestId":"425"}]
this is my response and I am storing that daysofInterest in hashmap...and getting using hashmap
But I want to get that in a array form
you can convert the json array into a java array with this
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
String[] myArray = list.toArray(new String[list.size()]);
then you can pass the array elements to your map. more info here Convert Json Array to normal Java Array
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
Days[] daysArray = gson.fromJson(jsonString, Days[].class);
Here is Gson library and here is example.
Hope this is useful.
yourstring is ["AA", "BB", "CC"]
if (!yourstring.equals("")) {
String[] type = yourstring
.replace("[", "")
.replace("]", "")
.replace("\"", "")
.split(",");
}
I want to save data into master - details table.First portion is for master table and last portion is for details table.I have got java.lang.String cannot be cast to [Ljava.lang.String .How to recover from this problem.How to assign map.get("step_id[]") into a string array String[] WfIds. I want to assign each value into distinct string array.
Controller Code
Map<String,Object> wfManager = new HashMap<String,Object>();
//************************Master data sent from view******************************//
wfManager.put("workflow_code",(request.getParameter("workflow_code")).toUpperCase());
wfManager.put("workflow_name",request.getParameter("workflow_name"));
wfManager.put("workflow_descr",request.getParameter("workflow_descr"));
wfManager.put("object_type_code",request.getParameter("object_type_code"));
//*********************Detail item data sent from view********************************//
wfManager.put("wf_block_id[]", request.getParameter("wf_block_id[]"));
wfManager.put("step_code[]" , request.getParameter("step_code[]"));
wfManager.put("step_name[]", request.getParameter("step_name[]"));
wfManager.put("doa_type_code[]", request.getParameter("doa_type_code[]"));
wfManager.put("doa_type_name[]", request.getParameter("doa_type_name[]"));
Service Code
public Map<String, String> insert(Map<String, Object> map) {
//************************Master data sent from view******************************//
Map<String, String> data = new HashMap<String, String>();
Workflow wf = new Workflow();
wf.setWorkflowCode((String)map.get("workflow_code"));
wf.setWorkflowName((String)map.get("workflow_name"));
wf.setWorkflowDescr((String)map.get("workflow_descr"));
wf.setObjectTypeCode((String)map.get("object_type_code"));
String[] WfIds = (String[]) map.get("step_id[]");
String[] wfBlockIds = (String[]) map.get("wf_block_id[]");
String[] wfsCodes = (String[]) map.get("step_code[]");
String[] stepNames = (String[]) map.get("step_name[]");
String[] doaTypeCodes = (String[]) map.get("doa_type_code[]");
String[] doaTypeNames = (String[]) map.get("doa_type_name[]");
List<WorkflowDetails> wfDetailsList = new ArrayList<WorkflowDetails>();
for(int i = 0; i< wfsCodes.length; i++){
WorkflowDetails wfDetails = new WorkflowDetails();
wfDetails.setWorkflowCode(wf.getWorkflowCode());
wfDetails.setWorkflowName(wf.getWorkflowName());
wfDetails.setWorkflowDescr(wf.getWorkflowDescr());
wfDetails.setWorkflowObjectTypeCode(wf.getObjectTypeCode());
wfDetails.setWorkflowObjectTypeName(wf.getObjectTypeName());
wfDetailsList.add(i,wfDetails);
}
wf.setSteps(wfDetailsList);
id = workflowManagerDAO.insertDoc(wf);
data.put("id", id);
return data;
}
Code for DAO:
#Transactional
#Override
public String insertDoc(Workflow wfManager) {
for(int i = 0; i < wfManager.getSteps().size(); i++){
WorkflowDetails wfDetails = new WorkflowDetails();
wfDetails = wfManager.getSteps().get(i);
sessionfactory.getCurrentSession().save(wfDetails);
sessionfactory.getCurrentSession().flush();
}
String id = (String) sessionfactory.getCurrentSession().save(wfManager);
sessionfactory.getCurrentSession().flush();
return id;
}
If you absolutely need to use request.getParameter(), you will have to convert your arrays to strings using a delimiter character, e.g. convert this
String[] array = { "John", "Peter", "Paul" };
to this
String plainTextArray = "John#Peter#Paul";
Then you will be able to pass you array values as String (the only type that getParameter() understands).
You can then restore them like this
String[] restoredArray = request.getParameter("plainTextArray").split("#");
Maybe you want to have a look at setAttribute() and getAttribute() which let you store any objects (including arrays). You can start here Difference between getAttribute() and getParameter()
I have a situation where in some JSON strings are seperated by a comma. For example I have a string which looks like this
{Valid JSON String},{Valid JSON String},{Valid JSON String}
I want to fetch each valid JSON string and store them in a ArrayList. How do I break the string?
You can do this :
List<JSONObject> result = new ArrayList<JSONObject>();
String s = "{Valid JSON String},{Valid JSON String},{Valid JSON String}";
JSONArray arr = new JSONArray("[" + s + "]");
for (int i = 0; i < arr.length(); i++)
{
result.add(arr.getJSONObject(i));
}
An then, with each JSONObject, you can do whatever you want
I have JSON object like
{
"projector":"no",
"video_conference":"no",
"polycom":"no",
"lcd":"no",
"digital_phone":"no",
"speaker_phone":"no"
}
How do I store the keys in one array and the values in a separate array?
Try GSON for converting your java object to json and vice versa.
Refer this link
http://code.google.com/p/google-gson/
You may try this.
String s = " { "projector":"no", "video_conference":"no", "polycom":"no", "lcd":"no", "digital_phone":"no", "speaker_phone":"no" }";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("projector");
Iterator iter = menu.keys();
String[] keyArr = new String();
String[] valArr = new String();
int count = 0;
while(iter.hasNext()){
keyArr[count] = (String)iter.next();
valArr[count] = menu.getString(key);
count +=1;
}
I like Jackson from http://codehaus.org/ for JSON parsing.
String text = "{ \"projector\":\"no\", \"video_conference\":\"no\", \"polycom\":\"no\", \"lcd\":\"no\", \"digital_phone\":\"no\", \"speaker_phone\":\"no\" }";
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(text, Map.class);
Set<String> k = map.keySet();
Collection<Object> v = map.values();
String[] keys = k.toArray(new String[k.size()]);
String[] values = v.toArray(new String[v.size()]);
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"}]