Parse JSON using amirdew/JSON library - android

I'm using amirdew/JSON library, which you can find here to parse my string to JSON.
The string I retrieved is this: https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal
This is the code I have at the moment, and it is not working and I believe that it is because of the keys...
public void ParseJson (String json){
JSON json2 = new JSON(json);
String firstTag = json2.key("query").key("pages").key("extract").stringValue();
txtInfo = findViewById(R.id.txtInfo);
txtInfo.setText(firstTag);
}
The firstTag variable is null because it can't retrieve any value. I want to retrieve the text inside "extracts". How can I do it? What keys do I need?

I suggest you to use the JSONObject which is already inside the SDK. You would use it like this:
String input = "..."; // your input
JSONObject obj = new JSONObject(input);
Strings extracts = obj.getJSONObject("query").getJSONObject("pages").getJSONObject("23033").getString("extract");

Related

Convert object a JSON object to string

I'm trying to convert a json object to a string using but I'm getting 'No Value for NAMES'. My code is as follows:
JSONObject jsonObject = new JSONObject(resp);
String c = jsonObject.getString("NAME");
msg("" + c);
Currently my object is as follows:
{"Names":[{"NAME":"Haircut"},{"NAME":"Blowdry"},{"NAME":"styling "},{"NAME":"treatment "},{"NAME":"braiding"}]}
How can I convert this data so that I may ingest the data into a listview dynamically.
Any help will be highly appreciated.
Names is and array in your JSON. So, firstly your should get it. Try this one:
JSONArray names = (JSONArray)jsonObject.get("Names");
((JSONObject) names.get(0)).get("NAME");

Is there any way to convert JSON String to query String in android?

I am stuck at converting a Json string into query string.
Actually, I want to create query string and from that query string I'll generate a SHA hash and set it in header to send to the server.
Please help!
Is your JSON String currently stored in a JSONObject? If not, this would be the best place to start. Something like this:
JSONObject json = new JSONObject(returnedString);
String firstValue= json.get(firstKey);
String secondValue = json.get(secondKey);
//And then construct your query string using the obtained values
Edit
Generic Method as suggested below...
Something like this:
public String getQueryString(String unparsedString){
StringBuilder sb = new StringBuilder();
JSONObject json = new JSONObject(unparsedString);
Iterator<String> keys = json.keys();
sb.append("?"); //start of query args
while (keys.hasNext()) {
String key = keys.next();
sb.append(key);
sb.append("=");
sb.append(json.get(key);
sb.append("&"); //To allow for another argument.
}
return sb.toString();
If you have more questions regarding JSONObject parsing in Android these docs are very helpful
On Android :
Uri uri=Uri.parse(url_string);
uri.getQueryParameter("para1");
On Android, the Apache libraries provide a Query parser:
http://developer.android.com/reference/org/apache/http/client/utils/URLEncodedUtils.html and http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html

How to get the multiple text from string in Android?

I am developing the Android for Xively. I get the following text data and store into string.
{"id":111111177,"title":"G-sensor","private":"true","feed":"https://api.xively.com/v2/feeds/111111177.json","auto_feed_url":"https://api.xively.com/v2/feeds/111111177.json","status":"frozen","updated":"2014-08-05T07:14:29.783670Z","created":"2014-08-01T08:29:17.156043Z","creator":"https://xively.com/users/x22819","version":"1.0.0","datastreams":[{"id":"GPIO1","current_value":"1","at":"2014-08-05T07:14:18.991421Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},{"id":"GPIO2","current_value":"0","at":"2014-08-05T07:14:29.783670Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},{"id":"GPIO3","current_value":"1","at":"2014-08-05T06:51:08.165217Z","max_value":"1.0","min_value":"1.0"},{"id":"GPIO4","current_value":"0","at":"2014-08-05T06:51:13.029452Z","max_value":"0.0","min_value":"0.0"},{"id":"GPIO5","current_value":"1","at":"2014-08-05T06:51:20.679123Z","max_value":"1.0","min_value":"1.0"},{"id":"GPIO6","current_value":"0","at":"2014-08-05T06:51:27.057369Z","max_value":"0.0","min_value":"0.0"}],"location":{"domain":"physical"},"product_id":"w8tuBsYf835kYTjDFz9w","device_serial":"DWJAXD6N7VDZ"}
There has id and the current_value in the above data , and I want to get the data of id and the current_value from the above text like following text.
GPIO1 1
GPIO2 0
GPIO3 1
GPIO4 0
GPIO5 1
GPIO6 0
How do I capture the the data of id and the current_value from the above text ?
Can somebody teach me how to do ?
Thank in advance.
Try this:
String resultJSON = "datastreams":[{"id":"GPIO1","current_value":"1","at":"2014-08-05T07:14:18.991421Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},
{"id":"GPIO2","current_value":"0","at":"2014-08-05T07:14:29.783670Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},
{"id":"GPIO3","current_value":"1","at":"2014-08-05T06:51:08.165217Z","max_value":"1.0","min_value":"1.0"},
{"id":"GPIO4","current_value":"0","at":"2014-08-05T06:51:13.029452Z","max_value":"0.0","min_value":"0.0"},
{"id":"GPIO5","current_value":"1","at":"2014-08-05T06:51:20.679123Z","max_value":"1.0","min_value":"1.0"},
{"id":"GPIO6","current_value":"0","at":"2014-08-05T06:51:27.057369Z","max_value":"0.0","min_value":"0.0"}],"location":{"domain":"physical"},"product_id":"w8tuBsYf835kYTjDFz9w","device_serial":"DWJAXD6N7VDZ"};
JSONObject jsonRoot = new JSONObject(resultJSON);
JSONArray jsonData = jsonRoot.getJSONArray("Data");
for(int i=0; i<jsonData.lenght;i++) {
JSONObject jsonOBject = jsonData.getJSONObject(i);
Log.d(TAG, "json ("+i+") = "+jsonOBject.toString());
// do what you want with your JSONObject , i.e :add it to an ArrayList of paresed result
String ID = jsonOBject.getString("id");
}
Hope this may help you
dataList = new ArrayList<HashMap<String, String>>();
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
myarray = jsonObj.getJSONArray("datastreams");
// looping through All myarray
for (int i = 0; i < myarray.length(); i++) {
JSONObject c = myarray.getJSONObject(i);
String id = c.getString("id");
String date = c.getString("at");
// tmp hashmap for single data
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_ID, id);
data.put(TAG_DATE, date);
// adding data to data list
dataList.add(data);
}
The data you have is actually a JSON so you can simply parse it to java POJO. I would suggest to use one of 2 most popular open source parsers GSON or Jackson.
What you have to do is:
Create java POJOs for chosen parser. To make it easier use this online tool http://www.jsonschema2pojo.org/
Copy generated java classes to your project.
Use JSON parser e.g. GSON
Let's say you named your main class as Example, with GSON you can parse it like this:
Gson gson = new Gson();
String data = ....//your JSON data
Example example = gson.fromJson(data, Example.class);
Data you would like to get will have own Java representation and will be available through getter method, e.g.:
List<Datastream> datastreams = example.getDatastreamList();
for (DataStream data : datastreams) {
String id = data.getId();
String currentValue = data.getCurrentValue();
}
Then you can do whatever you like. Please know that GSON can also read streams, so if you already parse stream to string you can skip it and pass that stream to Gson object directly.
If you don't want redundant POJOs or their parameters, you can remove them. GSON will handle it and simply ignore these values. Just make sure that data you are interested in keep the generated structure.
That's how I would do it.

Which is the best way to parse JSON data in Android?

I have JSON data to parse. The structure is not fixed, and sometimes it comes as a single string and other times as an array.
Currently, we are using the GSON library for parsing JSON, but are facing problems when it comes as an array.
For example:
1. {"msg":"data","c":300,"stat":"k"}
2. {
"msg": [
" {\"id\":2,\"to\":\"83662\",\"from\":\"199878\",\"msg\":\"llll\",\"c\":200,\"ts\":1394536776}"
],
"c": 200,
"stat": "k",
"_ts": 1394536776
}
In the example above, sometimes I get msg as a string and sometimes as an array.
Can anyone help me? If I decide to use JSON parsing, it will be very tedious because I have around 20+ API to parse and each API contains a mininum of 50 fields.
You can use JSONObject and JSONArray classes instead of GSON to work with JSON data
for the first example
String jsonStr = "{\"msg\":\"data\",\"c\":300,\"stat\":\"k\"}";
JSONObject jsonObj = new JSONObject(jsonStr);
String msg = jsonObj.getString("msg");
Integer c = jsonObj.getInteger("c");
String stat = jsonObj.getString("stat");
For the second example
String jsonStr = ... // "your JSON data";
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jsonArr = jsonObj.getJSONArray("msg");
JSONObject arrItem = jsonArr.getJSONObject(0);
//and so on
Also JSONObject class have method opString, opArray which does not throw exception if data you trying to get is not exist or have a wrong type
For example
JSONArray arr = jsonObj.optJSONArray("msg");
JSONObject msg = null;
if (arr != null) {
msg = arr.getJSONObject(0)
} else {
msg = jsonObj.getJSONObject("msg");
}
You can use Google GSON lib for directly parse the json to class object. This is easy and accurate.Okay do one thing both time code is different, if the code is 300 directly parse the json object without GSON. if the code is 200 the use the GSON (Define the similar java class)
String c= json.getString("c");
if(c.equals("300")
String message = status.getString("msg");
There are two ways to parce JSON.
Manually using Android OS JSON Parser Android JSON Parsing And Conversion
Using GSON Library [Library] (https://code.google.com/p/google-gson/downloads/list). This easy to handle if you know all the parameters and models of json response.
Refer the code snippet below to deserialize your json using Google's Gson library without exceptions.
String jsonStr = "your json string ";
Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();
JsonElement elem = jsonObj.get("msg");
if(elem.isJsonArray()) { //**Array**
ArrayList<MyMessage> msgList = gson.fromJson(elem.toString(), new TypeToken<List<MyMessage>>(){}.getType());
} else if(elem.isJsonObject()) { //**Object**
Note note = gson.fromJson(elem.toString(), MyMessage.class);
} else { //**String**
String note = elem.toString();
}
MyMessage class
public class MyMessage {
String to;
String from;
String msg;
int id;
int c;
long ts;
// Setters and Getters
}

Deserialize JSON with Gson in an object

I have a JSON string such as below. That comes from a Website (the URL outputs below to a page) which I'm using in an android application.
{"posts": [{"id":"0000001","longitude":"50.722","latitude":"-1.87817","position":"Someplace 1","altitude":"36","description":"Some place 1 "},{"id":"0000002","longitude":"50.722","latitude":"-1.87817","position":"Some PLace 2","altitude":"36","description":"Some place 2 description"}]}
I would like to deserialize this into a List where I can iterate through them later on the application. How do I do this? I have created a class with properties and methods and a List class as below and then using fromJson to deserialize it, but it returns NULL. Hope the question is clear and many thanks in advance.
ListClass
package dataaccess;
import java.util.List;
public class LocationList {
public static List<Location> listLocations;
public void setLocationList(List <Location> listLocations) {
LocationList.listLocations = listLocations;
}
public List<Location> getLocationList() {
return listLocations;
}
}
GSON
public LocationList[] getJsonFromGson(String jsonURL) throws IOException{
URL url = new URL(jsonURL);
String content = IOUtils.toString(new InputStreamReader(url.openStream()));
LocationList[] locations = new Gson().fromJson(content, LocationList[].class);
return locations;
}
You try to deserialize into an array of LocationList objects - that surely wasn't your intent, was it? The json snippet doesn't contain a list of lists.
I would drop the class LocationList (except it ought to be extened in future?), and use a pure List. Then, you have to create a type token like this:
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<ArrayList<Location>>() {}.getType();
List<Location> locations = new Gson().fromJson(content, type);
What if this JSON response can be parsed using native classes, here is a solution for the same:
String strJsonResponse="Store response here";
JsonObject obj = new JsonObject(strJsonResponse);
JsonArray array = obj.getJsonArray("posts");
for(int i=0; i<array.length; i++)
{
JsonObject subObj = array.getJsonObject(i);
String id = subObj.getString("id");
String longitude = subObj.getString("longitude");
String latitude = subObj.getString("latitude");
String position = subObj.getString("position");
String altitude = subObj.getString("altitude");
String description = subObj.getString("description");
// do whatever procedure you want to do here
}

Categories

Resources