Parsing json url - java

I am trying to create an image view from json url. I am getting the url using a for-loop in a string. I could not use that variable outside the for-loop. I tried constructing an arraylist inside the for-loop. This is what I am getting in the log.
Creating view...[[], [], [], [], [], [], [], [], [], []]
Here is my code.
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
// Log.v("url", "Creating view..." + json);
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_URL);
for (int i = 0; i < android.length(); i++) {
map = new ArrayList<HashMap<String, String>>();
JSONObject c = android.getJSONObject(i);
String name = c.getString(TAG_URL);
arraylist.add(map);
// Log.v("url", name);
}
Log.v("url", "Creating view..." + arraylist);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Here is the json:
http://www.json-generator.com/api/json/get/ciCLARKtKa?indent=4

When in doubt on how to create a POJO from a JSON, I'd recommend you to try this site:
http://www.jsonschema2pojo.org/
It outputs you a full java class that works for a given json type;
For most cases I'd recommend you to use this config (from the website above):
Source type: Json
Annotation style: None
And check ONLY use primitives.
Hope it helps !

hi do something as follows
JSONObject primaryObject = new JSONObject(//yours json string);
JSONArray primaryArray = primaryObject.getJSONArray("worldpopulation");
for (int i = 0; i < primaryArray.length(); i++) {
JSONObject another = primaryArray.getJSONObject(i);
String country = another.getString("country");
String flag = another.getString("flag");
int rank = another.getInt("rank");
String population = another.getString("population");
HashMap<String, String> map = new HashMap<String, String>();
map.put("flag", flag);
arraylist.add(i, map);
}

I think you missed put the values into MAP.
Try use like this
for (int i = 0; i < android.length(); i++) {
JSONObject c = android.getJSONObject(i);
// Storing each json item in variable
String flag = c.getString("flag");
HashMap<String, String> map = new HashMap<String, String>();
map.put("flag", flag);
arraylist.add(i, map);
}

Related

JSONObject from Google Maps parse in Java

I'm trying to parse Java Object to get data from a URL. I'm using getJSONObject and getString methods from org.json.JSONObject library but this it's not working. I'm doing something like...
JSONObject jsonCoord = json.getJSONObject("results")
.getJSONObject("geometry")
.getJSONObject("location");
coordinates[0] = jsonCoord.getString("lat");
coordinates[1] = jsonCoord.getString("lng");
JSON document I want to parse (Part 1)
JSON document I want to parse (Part 2)
How can I get "lat" and "lng" which is inside of "geometry"?
Here it is:
public static void main(String args[]) throws Exception {
String content = new String(Files.readAllBytes(Paths.get("test.json")), "UTF-8");
JSONObject json = new JSONObject(content);
JSONArray results = json.getJSONArray("results");
JSONObject result = (JSONObject) results.get(0); //or iterate if you need for each
JSONObject jsonCoord = result.getJSONObject("geometry").getJSONObject("location");
System.out.println(jsonCoord);
String[] coordinates = new String[2];
coordinates [0] = jsonCoord.getString("lat");
coordinates[1] = jsonCoord.getString("lng");
System.out.println(Arrays.asList(coordinates));
}

Convert JSON String to Arraylist for Spinner

I got my JSON string from my server which contains this values:
{"server_response":[{"violation":"Driving with No Helmet"},{"violation":"Try"}]}
What I'm trying to do is convert this JSON string into String Array or Arraylist
with the values of Driving with no Helmet and Try and use it as options on an Autocomplete Textview. But I cant seem to convert them correctly. Any help or tips on what I should do? Currently I am getting the JSON String from another activity and passing it to the activity where it should be used using this:
String json_string2 = getIntent().getExtras().getString("json_data");
Anyone has time I'm willing to learn. :) Thanks
PS: Managed to get it working. #Suhafer's answer is perfect. Thanks to everyone for the warm help! :)
I think first, you need to parse the json to get the list of string that you want:
String json_string2 = getIntent().getExtras().getString("json_data");
List<String> lStringList = new ArrayList<>();
try {
JSONObject lJSONObject = new JSONObject(json_string2);
JSONArray lJSONArray = lJSONObject.getJSONArray("server_response");
for (int i = 0; i < lJSONArray.length(); i++)
{
lStringList.add(
lJSONArray.getJSONObject(i).getString("violation"));
}
}
catch(Exception e)
{
e.printStackTrace();
}
Then, you need to set that list to your adapter:
ArrayAdapter<String> yourListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lStringList);
Next, implement the adapter to your AutoCompleteTextView.
lAutoCompleteTextView.setAdapter(lStringArrayAdapter);
Hope, that helps you.
Reading your comment I think you want this list to populate on an AutoCompleteTextView. I have written thoroughly what to do this will surely help If you follow these steps carefully.
First get the response and convert it to List<String> list = new ArrayList<>() format, Create a ArrayAdapter of this list by
yourListAdapter = new ArrayAdapter<String>(YourActivity.this,
android.R.layout.simple_list_item_1, list);
After this set your yourAutoCompleteTextBoxName.setAdapter(yourListAdapter);
In your Activity initialize this:
yourAutoCompleteTextBoxName.setOnEditorActionList(...){...}
also if you want your list to be clicked from AutoComplete TextView then do this:
yourAutoCompleteTextBoxName.setOnItemClickListener(...){...}
You can do this as below by using jettinson.jar
try {
String data = "{\"server_response\":[{\"violation\":\"Driving with No Helmet\"},{\"violation\":\"Try\"}]}";
JSONObject jsonObject = new JSONObject(data);
JSONArray temp = jsonObject.getJSONArray("server_response");
int length = temp.length();
if (length > 0) {
String[] recipients = new String[length];
for (int i = 0; i < length; i++) {
JSONObject nObject = new JSONObject(temp.getString(i));
recipients[i] = nObject.getString("violation");
}
}
} catch (JSONException ex) {
Logger.getLogger(JavaApplication2.class.getName()).log(Level.SEVERE, null, ex);
}
For getting your list of strings:
You can use Jackson's ObjectMapper class.
public class Data {
String violation;
...
}
List<Data> violations = objectMapper.readValue(json, new TypeReference<List<Data>>(){});
Below: "array" will have all the violations. (You will require some try / catch to surround with). Have a good day!
JSONObject json = new JSONObject(json_string2);
JSONArray violations = json.getJSONArray("server_response");
String[] array = new String[violations.length()];
for(int i = 0; i < violations.length(); i++) {
JSONObject violation = new JSONObject(violations.getString(i));
array[i] = violation.getString("violation");
}
You can use Gson library https://github.com/google/gson
Generate Plain Old Java Objects from JSON or JSON-Schema http://www.jsonschema2pojo.org/
YourJsonData jsonObject;
String json_string2 = getIntent().getExtras().getString("json_data");
Gson gson = new Gson();
jsonObject = gson.fromJson(json_string2, YourJsonData.class);
from jsonObject you can get your list i.e server_response array list.

How to acess the following property in this Json - JAVA

I have the following code that get the JSON in this URl :
https://www.googleapis.com/youtube/v3/search?key=AIzaSyCg3WitBUQl5ifC2QygQaZUPOSRMKfSD5E&channelId=UCPSDAF3Htm3AIxw4OUM3Lew&part=snippet,id&order=date&maxResults=20
I can acess the propierty "nextPageToken" and get your value with the following code:
JSONObject json = readJsonFromUrl(
"https://www.googleapis.com/youtube/v3/search?key=AIzaSyCg3WitBUQl5ifC2QygQaZUPOSRMKfSD5E&pageToken="
+ nextPageToken + "&channelId=" + new GetListAndPLayListYoutube().getIdUsuario()
+ "&part=snippet,id&order=date&maxResults=50");
System.out.println(json.get("nextPageToken"));
But i try Acess the property inside of "items" what is "videoId" and get the value of videoId, but not work, how can get the value of videoId
Try below code to get videoid from json String.
pass your json string object from parseJson() method:
private void parseJson(String responseString){
try {
Object object = new JSONTokener(responseString).nextValue();
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
Object object1 = jsonArray.getJSONObject(i);
if (object1 instanceof JSONObject) {
JSONObject jsonObject1 = (JSONObject) object1;
JSONObject jsonObject2= jsonObject1.optJSONObject("id");
String videoId = jsonObject2.optString("videoId");
System.out.println("videoId=" + videoId);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
It looks like you querying Youtube's Search API and extracting results from response. In which case, I would recommend using Google's API Client library (here) for Java instead of writing your own implementation.
Here are some examples of how to search Youtube using Google's API client and retrieve video information.

Json object to java arraylist

I have pass two values from ajax to my servlet.
I used
JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);
System.out.println(data);
and this is the output
{"0":"31/01/2017","1":"19/01/2017"}
Now I want to convert this data into a java arraylist but not really sure how.
I tried
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson(request.getReader(), JsonObject.class);
System.out.println(data);
JsonArray jsonArr = data.getAsJsonArray();
// jsonArr.
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i=0; i< jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
But got an error
java.lang.IllegalStateException: This is not a JSON Array.
Someone help me please? thanks.
Create instance of JsonArray then add json element to that array using key.
Here is your solution :
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson(request.getReader(), JsonObject.class);
System.out.println(data);
JsonArray jsonArr = new JsonArray();
for(Entry<String, JsonElement> entry : data.entrySet()) {
jsonArr.add(data.get(entry.getKey()));
}
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i = 0; i < jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
For a Json to be a valid JsonArray object you should have it to a proper format. Can you change your json string return from your ajax? If yes you should change it to something like this:
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson("{test: [{\"0\":\"31/01/2017\"},{\"1\":\"19/01/2017\"}]}", JsonObject.class);
System.out.println(data);
JsonArray jsonArr = data.getAsJsonArray("test");
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i=0; i< jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
If not you should parse it by your self and convert it to everything you want.

How do I create a JSONObject?

I'm trying to "create" a JSONObject. Right now I'm using JSON-Simple and I'm trying to do something along the lines of this (sorry if any typo's are made in this example JSON file)
{
"valuedata": {
"period": 1,
"icon": "pretty"
}
}
Right now I'm having issues finding on how to write valuedata into a JSON file through Java, what I did try was:
Map<String, String> t = new HashMap<String, String>();
t.put("Testing", "testing");
JSONObject jsonObject = new JSONObject(t);
but that just did
{
"Testing": "testing"
}
Whatr you want to do is put another JSONObject inside your JSONObject "jsonObject", in the field "valuedata" to be more exact. You can do this like that...
// Create empty JSONObect here: "{}"
JSONObject jsonObject = new JSONObject();
// Create another empty JSONObect here: "{}"
JSONObject myValueData = new JSONObject();
// Now put the 2nd JSONObject into the field "valuedata" of the first:
// { "valuedata" : {} }
jsonObject.put("valuedata", myValueData);
// And now add all your fields for your 2nd JSONObject, for example period:
// { "valuedata" : { "period" : 1} }
myValueData.put("period", 1);
// etc.
Following is example which shows JSON object streaming using Java JSONObject:
import org.json.simple.JSONObject;
class JsonEncodeDemo
{
public static void main(String[] args)
{
JSONObject obj = new JSONObject();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
StringWriter out = new StringWriter();
obj.writeJSONString(out);
String jsonText = out.toString();
System.out.print(jsonText);
}
}
While compile and executing above program, this will produce following result:
{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}

Categories

Resources