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()]);
Related
I have an service class as below:
public class RulesService {
#PersistenceContext
private EntityManager em;
public JSONArray getReportingTableData(String Query) {
List<Object> list = em.createNativeQuery(Query).getResultList();
return /*convert the above list as json array**/;
}
}
So, if the query is "select col1 as name,col2 as agefrom table1" then my jsonArray should be
[{"name":"test","age":"24"},{"name":"test1","age":"26"}]
I don't want to use pojo or entity class here, because the query will get change dynamically and there are many number of tables here, so I don't want to create seperate java class for each table.That is the reason am trying to make it as a JSONArray.
Can anyone please give me the right solution do it.
You could do that with Jackson's ObjectMapper. This tutorial is very interesting.
List<Object> list = em.createNativeQuery(Query).getResultList();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, list);
final byte[] data = out.toByteArray();
System.out.println(new String(data));
you can use ObjectMapper to do dynamically.
public JSONArray getReportingTableData(String Query) {
List<Object> list = em.createNativeQuery(Query).getResultList();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
String arrayToJson = objectMapper.writeValueAsString(list);
JSONArray array = new JSONArray(arrayToJson);
return /*convert the above list as json array**/;
}
I guess you want to do like bellow. your query result is list of array. [["test","24"],["test2","26"]] and you want to convert it to key-value
List<Map<String,String>> result = listOfarray.stream()
.map(arr->{
Map<String,String> map = new HashMap<>();
map.put("name",arr[0]);
map.put("age",arr[1]);
return map;
})
.collect(Collectors.toList());
Sorry guys, I might be late but someone might find this interesting and save his/her day.
Reference
[https://gist.github.com/baxtheman/44fd1601380d415eeec53d9e6d5587dc][1]
public List<ObjectNode> getQuery(
Integer anno,
Integer settimana) {
Query q = em.createNativeQuery(
"NATIVE SQL....",Tuple.class);
List<Tuple> results = q.getResultList();
List<ObjectNode> json = _toJson(results);
return json;
}
private List<ObjectNode> _toJson(List<Tuple> results) {
List<ObjectNode> json = new ArrayList<ObjectNode>();
ObjectMapper mapper = new ObjectMapper();
for (Tuple t : results)
{
List<TupleElement<?>> cols = t.getElements();
ObjectNode one = mapper.createObjectNode();
for (TupleElement col : cols)
{
one.put(col.getAlias(), t.get(col.getAlias()).toString());
}
json.add(one);
}
return json;
}
Its a late answer but got it when i needed it.
The pretty easy and simple thing worked for me is
String[] columns = {"id","name","salary","phone","address", "dob"};
String query = "SELECT id,name,salary,phone,address,dob from users ";
List<Object[]> queryResp = em.createNativeQuery(query).getResultList();
List<Map<String,String>> dataList = new ArrayList<>();
for(Object[] obj : queryResp) {
Map<String,String> row = new HashMap<>(columns.length);
for(int i=0; i<columns.length; i++) {
if(obj[i]!=null)
row.put(columns[i], obj[i].toString());
else
row.put(columns[i], "");
}
dataList.add(row);
}
//Creating the ObjectMapper object
ObjectMapper mapper = new ObjectMapper();
//Converting the Object to JSONString
String jsonString = mapper.writeValueAsString(dataList);
Right now I have the following JSON string:
"{"1":{"from":"540","to":"1020"},"2":{"from":"540","to":"1020"},"3":{"from":"540","to":"1020"},"4":{"from":"540","to":"1020"},"5":{"from":"540","to":"1020"},"6":{"from":"540","to":"1020"},"7":{"from":"540","to":"1020"}}"
and I want to parse it in Android Studio and iterate all just for this kind of result:
String day = monday;
int hourstart = from;
int hoursclose = to;
of course from and to means numbers. Does anyone know how construction of a JSON parser should look like?
Try this:
//here jsonString is your json in string format
JSONObject obj3=new JSONObject(jsonString);
JSONObject obj4=null;
//Getting all the keys inside json object with keys- from and to
Iterator<String> keys= obj3.keys();
while (keys.hasNext())
{
String keyValue = (String)keys.next();
obj4 = obj3.getJSONObject(keyValue);
//getting string values with keys- from and to
String from = obj4.getString("from");
String to = obj4.getString("to");
int hourstart = Integer.parseInt(from);
int hoursclose = Integer.parseInt(to);
System.out.println("From : "+ hourstart +" To : "+ hoursclose);
}
I am getting this string from a service. I want a map or json out of this. It should look like this.
Map output
Total time taken:226006
nodea:10615
nodez:5308'
String timingTrace = "Total time taken:226006.,"
+ "time spent in nodes:{\"nodea\":{\"timeTaken\":10615},\"nodez\":{\"timeTaken\":5308}}\"";
What I have tried so for is the below code. Can I do something better? Any library that can easily convert the above string to map.
if (timingTrace != null) {
arrayofTimeStamp = StringUtils.splitByWholeSeparator(StringUtils.remove(timingTrace, " "), ".,");
}
String[] totaltime = StringUtils.split(arrayofTimeStamp[0], ":")
Map<String,Object> timestamps = new HashMap<String, Object>();
timestamp.put(totaltime[0], totaltime[1]);
String[] nodetimestamp = StringUtils.splitByWholeSeparator(arrayofTimeStamp[1], "time spent in nodes:");
getMapped(nodetimestamp[1]);
public void getMapped(String json) throws JSONException, ParseException {
JSONObject obj = new JSONObject(json);
Iterator<String> keys = obj.keys();
while (keys.hasNext()) {
String key = keys.next();
String timetaken = JsonPath.read(json, "$." + key + ".timeTaken");
timestamp.put(key, timetaken);
}
}
You are using timestamp Map<> object in function getMapped(String json) that give you error because you haven't passed it you declare in function.
To get output you have mention change write below code instead of function getMapped(String json) :
JSONObject obj = new JSONObject(nodetimestamp[1]);
Iterator<String> keys = obj.keys();
while (keys.hasNext())
{
String key = keys.next();
String timetakenStr = obj.getString(key);
JSONObject child = new JSONObject(timetakenStr);
timestamps.put(key, child.getString("timeTaken"));
}
Using above code your Map<> will contain same what you mention.
OutPut :
{nodea=10615, Total time taken=226006, nodez=5308}
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 have problem when trying to parse with minimum value to map in Android.
There some sample JSON format with more information ex:
[{id:"1", name:"sql"},{id:"2",name:"android"},{id:"3",name:"mvc"}]
This that example most common to use and easy to use just use getString("id") or getValue("name").
But how do I parse to map using this JSON format with just only string and value minimum format to java map collection using looping. And because the string json will always different one with another. ex:
{"1":"sql", "2":"android", "3":"mvc"}
Thank
You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:
String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("menu");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}
My pseudocode example will be as follows:
JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();
for (each json in jsonArray) {
String id = json.get("id");
String name = json.get("name");
newJson.put(id, name);
}
return newJson;