How to extract JSON objects in android? - java

I am having some problems push values from a JSON object. Here is my code
try {
JSONObject mainObject = new JSONObject(data);
lat = mainObject.getString("lat");
lng = mainObject.getString("lon");
} catch (JSONException e) {
e.printStackTrace();
}
Here is an example of a JSON string I will use.
{
"resource":[
{
"lat":"15.456082",
"lon":"75.020660",
"devid":"TEST",
"time":"2019-03-12 11:11:20",
"speed":"0.51856",
"pInt":"60",
"result":"SOS"
}
]
}

try {
JSONObject mainObject = new JSONObject(data);
JSONArray jsonArray = mainObject.getJSONArray("resource");
JSONObject resourceObject = jsonArray.getJSONObject(0);
String lat = resourceObject.getString("lat");
String lng = resourceObject.getString("lon");
String devid = resourceObject.getString("devid");
String time = resourceObject.getString("time");
String speed = resourceObject.getString("speed");
String pInt = resourceObject.getString("pInt");
String result = resourceObject.getString("result");
} catch (Exception e) {
e.printStackTrace();
}

try {
JSONObject mainObject = new JSONObject(data);
JSONArray jsonArray = mainObject.getJSONArray("resource");
for(int i=0;i<jsonArray.length;i++ ){
JSONObject obj= josnArray.getJsonObject(i);
String lat = obj.getString("lat");
String lng = obj.getString("lon");
}
} catch (Exception e) {
e.printStackTrace();
}

Use Google's Gson instead. Here is full solution. It is life saving.
try {
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(data).getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("resource");
jsonObject = jsonArray.get(0).getAsJsonObject();
String lat = jsonObject.get("lat").getAsString();
String lng = jsonObject.get("lon").getAsString();
} catch (JsonIOException e) {
e.printStackTrace();
}

Related

How can i filter with a key through JSONArray

Im getting the next error:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:
class org.json.simple.JSONArray cannot be cast to class
org.json.simple.JSONObject (org.json.simple.JSONArray and
org.json.simple.JSONObject are in unnamed module of loader 'app')
The endpoint where im getting JSON is:
https://www.okex.com/api/spot/v3/instruments
I have searched about the error, I think the problem is that I am getting a JSONArray instead JSONObject, but I need to filter by key, as I need to get every "base_currency" from json.
Below is the original code which is giving me the error:
private String UrlBase = "https://www.okex.com/";
private URL url;
private String inline="";
private JSONObject jobj;
private JSONObject jobj1;
private Scanner sc;
private String Symbols = "api/spot/v3/instruments";
private String Param1= "base_currency";
private JSONArray arr;
private JSONArray arr1;
private JSONParser prs;
private HttpURLConnection conn;
private ArrayList Monedas = new ArrayList();
private Conexion conc = new Conexion();
public void CargarMonedasNuevasOkex() throws IOException {
try {
url = new URL(UrlBase+Symbols);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
conn = (HttpURLConnection)url.openConnection();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
conn.setRequestMethod("GET");
conn.connect();
int responsecode = conn.getResponseCode();
if(responsecode != 200) {
throw new RuntimeException("HttpResponseCode: " +responsecode);
}
else{
sc = new Scanner(url.openStream());
while(sc.hasNext())
{
inline+= sc.nextLine();
}
sc.close();
JSONParser parse = new JSONParser();
try {
jobj1 = (JSONObject) parse.parse(inline);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
arr1 = (JSONArray) jobj1.get(Param1);
System.out.println(arr.get(0));
for( int a=0; a<arr1.size(); a++ ) {
jobj1 = (JSONObject) arr1.get(a);
}
}
}
instead of
arr1 = (JSONArray) jobj1.get(Param1);
do
arr1=job1 ;//or jsut use the same variable
oh and
jobj1 = (JSONObject) parse.parse(inline);
should be
jobj1 = (JSONArray) parse.parse(inline);
then
for( int a=0; a<arr1.size(); a++ ) {
JSONOBject temp= arr1.get(a));
String currency= temp.get("base_currency")
}
basically in the link provided you get a jsonArray not an Object containing an Array
for your requirement getting value according key,you can try this below code it is modified according your JSON format.
JSONParser parser = new JSONParser();
Object object = parser.parse(inline);
JSONArray jsonArray = (JSONArray) object;
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject singleObject = (JSONObject) jsonArray.get(i);
System.out.println(singleObject.get("base_currency"));
}

How to encode jsonArray when added to jsonobject before sending to server using httpsurlconnection

I am getting the contact list from android and I want to send it to the server using HTTP URL connection. But every time, the added array to the jsonobject at the end, show up in string double quotes. How do I encode jsonobject, when it has jsonArray inside?
ArrayList<JSONObject> maps = new ArrayList<>();
String result ="";
try {
for (int i = 0; i < contactDetails.size(); i++) {
String FIRSTNAME =contactDetails.get(i).firstName;
String LASTNAME = contactDetails.get(i).lastName;
String CONTACT = contactDetails.get(i).contactNumber;
String EMAIL = contactDetails.get(i).email;
JSONObject contact = new JSONObject();
contact.put("firstName",FIRSTNAME );
contact.put("lastName",LASTNAME );
contact.put("contactNumber",CONTACT );
contact.put("email", EMAIL);
maps.add(contact);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject mainContact = new JSONObject();
try {
mainContact.put("token",token);
mainContact.put("contact",maps.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mainContact;
}
You have to use GSON library to make it in a easy way
Something like this
ArrayList<String> mArrayList = new ArrayList<String>();
mArrayList.add("First");
mArrayList.add("Second");
mArrayList.add("Third");
mArrayList.add("Fourtrh");
mArrayList.add("Fifth");
mArrayList.add("Sixth");
Log.i("Raw ArrayList", mArrayList);
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
String JSONObject = gson.toJson(mArrayList);
Log.i("Converted JSONObject",JSONObject);
Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
String prettyJson = prettyGson.toJson(mArrayList);
Log.i("Pretty JSONObject",prettyJson);

Android - org.json.simple.JSONObject cannot be cast to org.json.JSONObject

I am trying to sort scores coming from a JSONArray and output only the top 10. Here is my code.
try {
JSONArray jArray = new JSONArray(result);
List<String> jsonValues = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++)
jsonValues.add(jArray.getString(i));
Collections.sort(jsonValues);
JSONArray sortedJsonArray = new JSONArray(jsonValues);
for(int i=0;i<10;i++){
JSONObject jObject;
try {
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse((String) sortedJsonArray.get(i));
Score score =new Score();
score.setId(obj.getInt("Id"));
score.setPlayerId(obj.getInt("PlayerId"));
score.setHiScore(obj.getInt("HiScore"));
tempList.add(score);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I wanted to parse the sortedJsonArray into JSONObject that's why I used org.json.simple.JSONObject, but It says it cannot be cast to JSONObject. I tried using org.json.simple.JSONObject datatype for obj but I got this error
The method getInt(String) is undefined for the type JSONObject
I am retrieving data from a web server
List<Score> tempList = new ArrayList<Score>();
HttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(EndPoint+"/Scores");
String result="";
HttpResponse response;
try {
response = client.execute(getRequest);
HttpEntity entity = response.getEntity();
if(entity!=null){
InputStream instream = entity.getContent();
StreamConverter sc= new StreamConverter();
result= StreamConverter.convertStreamToString(instream);
instream.close();
}
EDIT
I realized that I could just parse JSONArray to string using (String) and not use JSONParse. -____-
jObject = new JSONObject((String) sortedJsonArray.get(i));
Try this for parsing :
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString(KEY_SUCCESS).equals("true")) {
preDefineAlertList = new ArrayList<HashMap<String, String>>();
JSONArray jsonArray = jsonObject.getJSONArray("Data");
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> mapNew = new HashMap<String, String>();
JSONObject obj = jsonArray.getJSONObject(i);
// Log.d("obj", obj.toString());
alert_message = obj.getString(Constants.Params.MESSAGE);
id = obj.getString(Constants.Params.ID);
mapNew.put("message", message);
mapNew.put("id",id);
// Log.d("mapNew", mapNew.toString());
preDefinetList.add(mapNew);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
you are using the JSONObject of a library which uses Default JSONObject and does some manipulations to it.
You are using the JSONObject of that library from the package of simple.Jsonobject and you are trying to compare it to default json.Jsonobject .
Try yo see what exactly you are doing to cause it . It will help you not just in this case but in future as well.

Java volley empty json object

On a response I expect a JSON string.
But now I have to provide a key for the Object I want to retrieve. The response I want is just simple {"xx":"xx","xx":"xx"} format, without an array with a name like this {"XX":["xx":"xx"]}. How can I fetch the JSON without having to provide a parameter. In short, I just want to read the JSON response I get without having to give a parameter.
protected JSONObject parseJSONMeth() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
JSONObject jo = users.getJSONObject(0);
return jo;
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
Why don't you use the GSON https://sites.google.com/site/gson/gson-user-guide :
Gson gson = new GsonBuilder().create();
User result = new User();
result=(gson.fromJson(json, User .class));
And for users List :
private static List<User> getDataFromJson(String json) {
Gson gson = new GsonBuilder().create();
List<User> result = null;
try {
JSONObject posts=new JSONObject(json);
result = gson.fromJson(posts.toString(), new TypeToken<List<User>>(){}.getType());
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}

What am I doing wrong in this parsing?

I am currently parsing through reddit.com/.json with Google Gson and having some trouble. After doing some research I found a way to parse through json with Gson without making a lot of classes. I am using this method. Here is my code so far:
import java.io.*;
import java.net.*;
import com.google.gson.*;
public class Subreddits {
public static void main(String[] args) {
URL u = null;
try {
u = new URL("http://www.reddit.com/.json");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection yc = null;
try {
yc = u.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String json = null;
StringBuilder sb = new StringBuilder();
try {
while ((json = in.readLine()) != null){
sb.append(json);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
json = sb.toString();//String of json
System.out.println(json);
//I want to get [data][children][data][subreddit]
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonObject locObj = rootObj.getAsJsonObject("data").getAsJsonObject("children").getAsJsonObject("data");
String subreddit = locObj.get("subreddit").getAsString();
System.out.println(subreddit);
}
}
You are trying to get the element "children" as a JsonObject, but it is a JsonArray because it is surrounded by [ ]...
Try something like this:
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
//Here is the change
JsonObject locObj = rootObj
.getAsJsonObject("data")
.getAsJsonArray("children")
.get(0)
.getAsJsonObject()
.getAsJsonObject("data");
String subreddit = locObj.get("subreddit").getAsString();
Note: I assume that you only want to get the data of the first element of the "children" array, since it seems that it is what you want looking at your code and mainly looking at this other question of yours.
The children object returns an Array that you must iterate.
public static void main(String[] args) {
URL u = null;
try {
u = new URL("http://www.reddit.com/.json");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection yc = null;
try {
yc = u.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String json = null;
StringBuilder sb = new StringBuilder();
try {
while ((json = in.readLine()) != null) {
sb.append(json);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
json = sb.toString();// String of json
System.out.println(json);
// I want to get [data][children][data][subreddit]
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonArray locObj = rootObj.getAsJsonObject("data").getAsJsonArray("children");
/* Iterating children object */
Iterator<JsonElement> iterator = locObj.iterator();
while(iterator.hasNext()){
JsonElement element = iterator.next();
JsonElement subreddit = element.getAsJsonObject().getAsJsonObject("data").get("subreddit");
System.out.println(subreddit.getAsString());
}
}
You don't need to create try..catch block for every expression that can throw an exception.
JsonParser.parse() method accepts Reader (e.g. InpustStreamReader) instance so you don't have to read JSON on your own.
root[data][children] is an array of objects so you'll have to iterate over them in order to gain access to individual objects.
I believe you want to read all [subredit]s into some sort of collection, Set I pressume?
public static void main(String[] args) {
try {
Set<String> subreddits = new HashSet<>();
URL url = new URL("http://www.reddit.com/.json");
JsonParser parser = new JsonParser();
JsonObject root = parser.parse(new InputStreamReader(url.openConnection().getInputStream())).getAsJsonObject();
JsonArray children = root.getAsJsonObject("data").getAsJsonArray("children");
for (int i = 0; i < children.size(); i++) {
String subreddit = children.get(i).getAsJsonObject().getAsJsonObject("data").get("subreddit").getAsString();
subreddits.add(subreddit);
}
System.out.println(subreddits);
} catch (IOException e) {
e.printStackTrace();
}
}
This code returns:
[IAmA, worldnews, technology, news, todayilearned, gaming, AskReddit, movies, videos, funny, bestof, science, WTF, politics, aww, pics, atheism, Music, AdviceAnimals]

Categories