I am trying to use the 2nd value of each of my JSON elemnts and use it in a array of web urls. What I am trying to end of with is a array of urls that include the image names from my json data below.
JSON Data:
[["1","Dragon Neck Tattoo","thm_polaroid.jpg","polaroid.jpg"],["2","Neck Tattoo","thm_default.jpg","default.jpg"],["3","Sweet Tattoo","thm_enhanced-buzz-9667-1270841394-4.jpg","enhanced-buzz-9667-1270841394-4.jpg"]]
MainActivity:
Bundle bundle = getIntent().getExtras();
String jsonData = bundle.getString("jsonData");
try {
//THIS IS WHERE THE VALUES WILL GET ASSIGNED
JSONArray jsonArray = new JSONArray(jsonData);
private String[] mStrings=
{
for(int i=0;i<jsonArray.length();i++)
{
"http://www.mywebsite.com/images/" + jsonArray(i)(2),
}
}
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this, mStrings);
list.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
As I mentioned in a previous answer, a JSONArray is just an object, not a numerically-indexable array. It looks like you're having trouble with basic Java syntax, as well.
If you actually want to use a String[], not a List<String>:
private String[] mStrings = new String[jsonArray.length()];
for (int i=0; i<jsonArray.length(); i++)
{
String url = jsonArray.getJSONArray(i).getString(2);
mStrings[i] = "http://www.mywebsite.com/images/" + url;
}
If the LazyAdapter you're using can take a List, that'll be even easier to work with:
private List<String> mStrings = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++)
{
String url = jsonArray.getJSONArray(i).getString(2);
mStrings.add("http://www.mywebsite.com/images/" + url);
}
Related
I have to post this type of data into Json. I don't want to convert cat in string. I only want single quote of item enclosing with double quote.
{"p02bvsd":"cal_dis","ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}}
My Json
JSONObject jsonobject1 = new JSONObject();
jsonobject.put("p02bvsd", "cal_dis");
jsonobject.put("ovpsc7s", jsonobject1);
jsonobject1.put("cat", hCategory);
Here hCategory is Hashset.
I want to json like this
{"p02bvsd":"cal_dis","ovpsc7s":{"cat": ["'Furniture'", "'Bikes'", "'Others'" ]}}
JSONObject jsonobject = new JSONObject();
jsonobject.put("p02bvsd", "cal_dis");
JSONObject jsonobject1 = new JSONObject();
List <String> list = new ArrayList <String>();
list.add("Furniture");
list.add("Bikes");
list.add("Others");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
try {
jsonobject1.put("cat", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jsonobject.put("ovpsc7s", jsonobject1);
String myString = "{\"p02bvsd\":\"cal_dis\",\"ovpsc7s\":{\"cat\":[\"\'Furniture\'\", \"\'Bikes\'\", \"\'Others\'\"]}}";
JSONObject wholeThing = new JSONObject(myString); // contains {"p02bvsd":"cal_dis","ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}}
JSONObject jsonp02bvsd = wholeThing.getJSONObject("p02bvsd"); // contains {"p02bvsd":"cal_dis"}
JSONObject jsonovpsc7s = wholeThing.getJSONObject("ovpsc7s"); // contains {"ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}
JSONArray jsonCatArray = jsonp02bvsd.getJSONArray("cat"); // contains ["'Furniture'", "'Bikes'", "'Others'"]
String first = jsonCatArray.getString(0); // contains 'Furniture'
strResponse = {"GetCitiesResult":["1-Vizag","2-Hyderbad","3-Pune","4-Chennai","9-123","11-Rohatash","12-gopi","13-Rohatash","14-Rohatash","10-123"]}
JSONObject json = new JSONObject(strResponse);
// get LL json object
String json_LL = json.getJSONObject("GetCitiesResult").toString();
Now i want to convert the json string to List in andriod
Please make sure your response String is correct format, if it is, then try this:
try {
ArrayList<String> list = new ArrayList<String>();
JSONObject json = new JSONObject(strResponse);
JSONArray array = json.getJSONArray("GetCitiesResult");
for (int i = 0; i < array.length(); i++) {
list.add(array.getString(i));
}
} catch (Exception e) {
e.printStackTrace();
}
Simply using Gson library you can convert json response to pojo class.
Copy the json string to create pojo structure using this link: http://www.jsonschema2pojo.org/
Gson gson = new Gson();
GetCitiesResult citiesResult = gson.fromJson(responseString, GetCitiesResult.class);
It will give the GetCitiesResult object inside that object you get a list of your response like
public List<String> getGetCitiesResult() {
return getCitiesResult;
}
Call only citiesResult.getGetCitiesResult(); it will give a list of cities.
You can also use this library com.squareup.retrofit2:converter-gson:2.1.0
This piece of code did the trick
List<String> list3 = json.getJSONArray("GetCitiesResult").toList()
.stream()
.map(o -> (String) o)
.collect(Collectors.toList());
list3.forEach(System.out::println);
And printed:
1-Vizag
2-Hyderbad
3-Pune
4-Chennai
9-123
11-Rohatash
12-gopi
13-Rohatash
14-Rohatash
10-123
below is code:
private void parse(String response) {
try {
List<String> stringList = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("GetCitiesResult");
for (int i=0; i <jsonArray.length(); i++){
stringList.add(jsonArray.getString(i));
}
Log.d ("asd", "--------"+ stringList);
} catch (Exception e) {
e.printStackTrace();
}
}
Hope it will help.
Output is when print list :
--------[1-Vizag, 2-Hyderbad, 3-Pune, 4-Chennai, 9-123, 11-Rohatash, 12-gopi, 13-Rohatash, 14-Rohatash, 10-123]
Ok you must know first something about JSON
Json object is be {// some attribute}
Json Array is be [// some attribute]
Now You have
{"GetCitiesResult":["1-Vizag","2-Hyderbad",
"3-Pune","4-Chennai","9-123","11-Rohatash",
"12-gopi","13-Rohatash","14-Rohatash","10-123"]}
That`s Means you have JSON array is GetCitiesResult
which have array of String
Now Try this
JSONObject obj = new JSONObject(data);
JSONArray loadeddata = new JSONArray(obj.getString("GetCitiesResult"));
for (int i = 0; i <DoctorData.length(); i++) {// what to do here}
where data is your String
I am trying to parse a JsonArray and get its values but I am gettign error when I use
jitem.getString("firstitem");
or
jitem.getJSONObject("firstitem");
or
jitem.get("firstitem");
Following is the code snippet.
JSONArray arr_items = new JSONArray(str);
if(arr_items!=null && arr_items.size()>0){
for(int i=0;i<arr_items.size();i++){
JSONObject jitem = arr_items.getJSONObject(i);//works fine till here
jitem.getString("firstitem"); //throws exception here
}
This is the JSONArray that I am parsing
[{"firstitem":"dgfd","secondtitem":"dfgfdgfdg","thirditem":"fdgfdgdf#sjhasjkdsha.com","fourthitem":"jkksdjklsfjskj"}]
what I am doing wrong? How to get these values by using keys?
Update:Note This array and its parameters are not null at all. They all have valid values.
First check arr_items is not empty.
Then, try surrounding your snippet with try/catch :
try {
your snippet
} catch (JSONException e) {
e.printStackTrace();
}
Check below
String json ="{'array':" + "[{'firstitem':'dgfd','secondtitem':'dfgfdgfdg','thirditem':'fdgfdgdf#sjhasjkdsha.com','fourthitem':'jkksdjklsfjskj'}]"+ "}";
JSONObject myjson = new JSONObject(json);
JSONArray the_json_array = myjson.getJSONArray("array");
int size = the_json_array.length();
// ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
// arrays.add(another_json_object);
System.out.println(another_json_object.get("firstitem"));
}
it require some array name so appended array name to it , if you want without it you have to add GSON.
I am trying to parse a JSON schema and I need to get all the image links from the JSONArray and store it in a java array. The JSONArray looks like this:
How can I get only the number of strings in the image array for e.g. In this case it should be 4? I know how to get the full length of array but how can I only get the number of strings?
UPDATE:
I am simply parsing it using the standard JSON parser for android. The length of JSONArray can be calculated using:
JSONArray imageArray = hist.getJSONArray("image");
int len = imageArray.length();
len will be equal to 9 in this case.
I'm not sure if there's a better way (there probably is), but here's one option:
According to the Android docs, getJSONObject will throw a JSONException if the element at the specified index is not a JSON object. So, you can try to get the element at each index using getJSONObject. If it throws a JSONException, then you know it's not a JSON object. You can then try and get the element using getString. Here's a crude example:
JSONArray imageArray = hist.getJSONArray("image");
int len = imageArray.length();
ArrayList<String> imageLinks = new ArrayList<String>();
for (int i = 0; i < len; i++) {
boolean isObject = false;
try {
JSONArray obj = imageArray.getJSONObject(i);
// obj is a JSON object
isObject = true;
} catch (JSONException ex) {
// ignore
}
if (!isObject ) {
// Element at index i was not a JSON object, might be a String
try {
String strVal = imageArray.getString(i);
imageLinks.add(strVal);
} catch (JSONException ex) {
// ignore
}
}
}
int numImageLinks = imageLinks.size();
I have a web service that performs a database query, converts the result set to a JSON String and returns the strung to the client. This is the code for the converter (I got it from http://biercoff.com/nice-and-simple-converter-of-java-resultset-into-jsonarray-or-xml/):
public static String convertToJSON(ResultSet resultSet)
throws Exception {
JSONArray jsonArray = new JSONArray();
while (resultSet.next()) {
int total_rows = resultSet.getMetaData().getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 0; i < total_rows; i++) {
obj.put(resultSet.getMetaData().getColumnLabel(i + 1)
.toLowerCase(), resultSet.getObject(i + 1));
}
jsonArray.add(obj);
}
return jsonArray.toJSONString();
}
In the client application when I print the returned string it is in the following format:
[{"Column1":0.333333,"Column2":"FirmA"},{"Column1":0.666667,"Column2":"FirmB"}]
so far all is good. The problem I am having is converting the returned string into a JSON array. I tried this:
JSONArray arr = new JSONArray(JSON_STRING);
but got the following error message: constructor JSONArray in class JSONArray cannot be applied to given types. I tried to first convert in into a JSON object like so:
JSONObject obj = new JSONObject(JSON_STRING);
but got the following error: incompatible types: String cannot be converted to Map. What am I doing wrong? Thanks.
Apparently the problem was with the json library that I was using. Once I used the
import org.json.JSONArray;
it all worked out well. I was able to convert the returned string to an array using
JSONArray arr = new JSONArray(JSON_STRING);
and to iterate through the values I used the code provided in this answer: Accessing members of items in a JSONArray with Java which I reproduce here for simplicity:
for (int i = 0; i < arr.length(); ++i) {
JSONObject rec = arr.getJSONObject(i);
int id = rec.getInt("id");
String loc = rec.getString("loc");
// ...
}
well you need to do it by this way for example
String jsonText = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
try {
JSONArray array = new JSONArray(jsonText);
System.out.println(array);
System.out.println(array.length());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Check the correct library used. The mess is that org.json.simple is often suggested by IDE as default for JSONObject and JSONArray.
You can find a link to latest jar for org.json library above.