JSON Array of strings (no objects), extracting data - android

I have a long JSON string representing a string[] array being returned from a WCF service. The array elements are simply strings, they are not objects. This is an example of the return data
["1|ArrayElement1","2|ArrayElement2","3|ArrayElement3"..."n|ArrayElementn"]
I don't mind the index being included in the string, but I need to parse the strings into an ArrayList in Android so that I can adapt it to a ListView.
Since these technically aren't JSONObjects, how can I iterate over them and extract the string from each array element?

this is a valid JSON array of strings, you can parse it normally like this
JSONArray jsonStrings = json.getJSONArray("items");
String strings[] = new String[jsonStrings.length()];
for(int i=0;i<strings.length;i++) {
strings[i] = jsonStrings.getString(i);
}

Maybe this post can help you out:
JSON Array iteration in Android/Java
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i = 0; i < settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
JSONArray names= json.names();
JSONArray values = json.toJSONArray(names);
for(int i = 0 ; i < values.length(); i++){
if(names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if(names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if(names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if(names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if(names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if(names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}

Just to clarify, as I understand it you are receiving a JSON array of strings which are strings of valid JSON prefixed with the array index and a pipe character?
First, I would suggest contacting the creator of this abomination and lecturing them on violating standards. If they won't listen, talk to their bosses. This kind of thing is unacceptable in my opinion and needs to stop.
Second, I'd suggest doing something like this:
string[] element_strings = JSON.deserialize(WCF_string_result);
object[] elements = new object[element_strings.length];
for(int x = 0; x < elements.length; x++)
{
int pipeIndex = element_strings.indexOf("|");
elements[x] = JSON.deserialize(element_strings[x].substr(pipeIndex + 1));
}
Of course this assumes you have some kind of method for deserializing strings of JSON objects. If you don't I'd recommend using the built in library available in Android:
http://developer.android.com/reference/org/json/package-summary.html

If you want to extract specific value from it using Java8 stream on JSONArray. Then this code will help.
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.json.JSONArray;
public class JsonArrayTest {
public static void main(String[] args) {
System.out.println("Output - "+ getValue("[{\"id\":\"11\",\"username\":\"ABC\"},{\"id\":\"12\",\"username\":\"ABC\"}]\""));
System.out.println("Output - "+ getValue("[{\"id\":\"13\",\"username\":\"XYZ\"}]\""));
}
private static String getValue(String input) {
JSONArray jsonArray = new JSONArray(input);
return IntStream
.range(0, jsonArray.length()).mapToObj(obj -> jsonArray.getJSONObject(obj))
.filter(filterObj -> filterObj.getString("id") != null && "12".equals(filterObj.getString("id")))
.map(finalObj -> finalObj.getString("username")).collect(Collectors.joining(""));
}
}
Note: This is just an example how can you extract a specific value from JSONArry using stream APIs. You can change the filter condition or drop it according to your requirement.

Related

get JSONArray data inside JSONArray

I need to get "examples" data that is an array inside of 'results'
JSON FILE
and append it to a string. What would be the easiest way to do that?
this is how i would get "definitions"
private JSONObject queryResults;
...
...
String finalResults = "";
JSONArray results = queryResults.getJSONArray("results");
for(int i = 0; i < results.length(); i++){
JSONObject item = results.getJSONObject(i);
finalResults += item.getString("definition") + " ";
}
As this topic is related to Android application, the easiest way to get the mentioned value without using any additional libraries is to check if JSONObject inside the for-loop has attribute definitions and get the value as a String.
You can go with it like this
String finalExamples = "";
JSONArray results = queryResults.getJSONArray("results");
for (int i=0; i < results.length(), i++) {
JSONObject item = results.getJSONObject(i);
if (item.has("examples")) {
examples += item.getString("examples");
}
}
I assumed that you don't want to update your result String value if examples is not available in the JSONObject.
If you want to handle other cases, for example when "examples" is available in the object but is null or is set to empty String you can use other methods of JSONObject to check it.
More info about working with JSONObjects you can find in the documentation

JSON data list dynamic

I am working in Android just for a heads up. I was able to retrieve JSON data but now I have come to the point where there are multiples. Example:
"workers":[
{
"id":3357,
"username":"Unreliable.worker",
"password":"x",
"monitor":0,
"count_all":41,
"count_all_archive":0,
"hashrate":477,
"difficulty":106.56
},
{
"id":4061,
"username":"Unreliable.worker2",
"password":"x",
"monitor":0,
"count_all":0,
"count_all_archive":null,
"hashrate":0,
"difficulty":0
}
would I have to do a for loop or is there another way to do it?
This is the code that I am using now to get them:
JSONObject workersJSONObject = personalJSONObject.getJSONObject("workers");
but I don't know how I would get for each and separate them. I'll get them by using:
id= workersJSONObject.getDouble("id");
[] in JSON refers to a JSON array. You could use something like:
JSONArray workersJSONArray = personalJSONObject.getJSONArray("workers");
Then loop through each item as (basically get each object inside array):
for (int i = 0; i < workersJSONArray.length(); i++) {
JSONObject workersJSONObject = workersJSONArray.getJSONObject(i);
// parse object just like before
}
On JSON, {} defines an object, [] defines an array instead. if you want details. see this and JSONArray
sample:
JSONArray workersJSOnArray = new JSONArray(stringData);
or
JSONArray workersJSOnArray = personalJSONObject.getJSONArray("workers");
/* THen you can loop from each data you want */
int len = workersJSOnArray.length();
for (int i = 0; i < len; i++)
{
JSONObject item = workersJSOnArray.optJSONObject(i);
int id = item.getInt ("id");
.....
}

How to parse JSON without title object in Android?

I've a json output which returns something like this :
[
{
"title":"facebook",
"description":"social networking website",
"url":"http://www.facebook.com"
},
{
"title":"WoW",
"description":"game",
"url":"http://us.battle.net/wow/"
},
{
"title":"google",
"description":"search engine",
"url":"http://www.google.com"
}
]
I am familiar with parsing json having the title object, but i've no clue about how to parse the above json as it is missing the title object. Can you please provide me with some hints/examples so i can check them and work on parsing the above code?
Note : I've checked a similar example here but it doesn't have a satisfactory solution.
Your JSON is an array of objects.
The whole idea around Gson (and other JSON serialization/deserialization) libraries is that you wind up with your own POJOs in the end.
Here's how to create a POJO that represents the object contained in the array and get a List of them from that JSON:
public class App
{
public static void main( String[] args )
{
String json = "[{\"title\":\"facebook\",\"description\":\"social networking website\"," +
"\"url\":\"http://www.facebook.com\"},{\"title\":\"WoW\",\"description\":\"game\"," +
"\"url\":\"http://us.battle.net/wow/\"},{\"title\":\"google\",\"description\":\"search engine\"," +
"\"url\":\"http://www.google.com\"}]";
// The next 3 lines are all that is required to parse your JSON
// into a List of your POJO
Gson gson = new Gson();
Type type = new TypeToken<List<WebsiteInfo>>(){}.getType();
List<WebsiteInfo> list = gson.fromJson(json, type);
// Show that you have the contents as expected.
for (WebsiteInfo i : list)
{
System.out.println(i.title + " : " + i.description);
}
}
}
// Simple POJO just for demonstration. Normally
// these would be private with getters/setters
class WebsiteInfo
{
String title;
String description;
String url;
}
Output:
facebook : social networking website
WoW : game
google : search engine
Edit to add: Because the JSON is an array of things, the use of the TypeToken is required to get to a List because generics are involved. You could actually do the following without it:
WebsiteInfo[] array = new Gson().fromJson(json, WebsiteInfo[].class);
You now have an array of your WebsiteInfo objects from one line of code. That being said, using a generic Collection or List as demonstrated is far more flexible and generally recommended.
You can read more about this in the Gson users guide
JSONArray jsonArr = new JSONArray(jsonResponse);
for(int i=0;i<jsonArr.length();i++){
JSONObject e = jsonArr.getJSONObject(i);
String title = e.getString("title");
}
use JSONObject.has(String name) to check an key name exist in current json or not for example
JSONArray jsonArray = new JSONArray("json String");
for(int i = 0 ; i < jsonArray.length() ; i++) {
JSONObject jsonobj = jsonArray.getJSONObject(i);
String title ="";
if(jsonobj.has("title")){ // check if title exist in JSONObject
String title = jsonobj.getString("title"); // get title
}
else{
title="default value here";
}
}
JSONArray array = new JSONArray(yourJson);
for(int i = 0 ; i < array.lengh(); i++) {
JSONObject product = (JSONObject) array.get(i);
.....
}

How to convert array of value objects to json?

I have an array of classes of this type:
public class IndexVO {
public int myIndex;
public String result;
}
And this is my array:
IndexVo[] myArray = { indexvo1, indexvo2 };
I want to convert this array to json, any idea how?
This wouldn't be as easy as JSONArray mJSONArray = new JSONArray(Arrays.asList(myArray)) since your array contains objects of unsupported class. Hence you will have to make a little more effort:
JSONArray mJSONArray = new JSONArray();
for (int i = 0; i < myArray.length; i++)
mJSONArray.put(myArray[i].toJSON());
And add toJSON() method to your IndexVo class:
public JSONObject toJSON() {
JSONObject json = new JSONObject();
...
//here you put necessary data to json object
...
return json;
}
However, if you need to generate JSON for more than one class, then consider libraries which do it automatically, flexjson, for example.

how to be easier to analyse the json

i want to analyse the json just like:
[{"id":"ssq","name":"双色球","term":"2010092","date":"2010-08-12 19:15","numbers":{"normal":"3,13,19,27,28,30","special":"2"},"jackpot":"30000000"},{"id":"3d","name":"3D","term":"2010216","date":"2010-08-12 19:55","numbers":{"normal":"6,8,8"},"jackpot":"-"},{"id":"qlc","name":"七乐彩","term":"2010093","date":"2010-08-11 20:45","numbers":{"normal":"08,09,10,11,16,21,27","special":"26"},"jackpot":"0"},{"id":"dfljy","name":"东方6+1","term":"2010093","date":"2010-08-14 18:30","numbers":{"normal":"4,1,3,9,7,2","special":"羊"},"jackpot":"12866531"},{"id":"swxw","name":"15选5","term":"2010217","date":"2010-08-12 18:45","numbers":{"normal":"1,3,5,13,15"},"jackpot":"5693612"},{"id":"ssl","name":"时时乐","term":"20100811-23","date":"2010-08-12 10:27","numbers":{"normal":"6,7,1"},"jackpot":"-"},{"id":"klsf","name":"快乐十分","term":"201021649","date":"2010-08-11 22:00","numbers":{"normal":"5,11,12,14,20"},"jackpot":"-"},{"id":"klsc","name":"快乐双彩","term":"2010215","date":"2010-08-10 21:25","numbers":{"normal":"12,23,10,15,7,3","special":"11"} ,"jackpot":"198059"}]
i want to gain all of them,but the data is so many,so whether i need to create 8 kinds of class to store the data,so to be easier to use.thanks!
To add to cfei's response, one thing that I've done when processing JSON responses from Flickr, is create a new class particularly for that type of object.
So for yours, just playing it by ear, something like the below:
public class Lottery() {
private JSONObject json;
private String id;
private String name;
private String term;
private String date;
private String norm_numbers;
private String spec_numbers;
private String jackpot;
public Lottery(JSONObject json) {
this.json = json;
}
public void setId()
{
try {
id = json.getString("id");
} catch (JSONException e) {
id = "";
}
}
//additional getters and setters, etc.
}
This way, you can make an array of objects, and access the fields like so:
//...get a JSONObject from the array...
Lottery lottery = new Lottery(json);
Log.v("ID", lottery.id);
Log.v("Name", lottery.name);
and so on.
Do you mean that you want to iterate through each of the eight JSONObjects in this JSONArray? You need to create a JSONArray object with the input string you posed above (let's call it "response", as used below) and then iterate through the array to get each JSONObject it contains. For example:
JSONArray array = new JSONArray(response);
for(int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
// do something with obj
// example: to get the id for a particular object, use obj.getString("id")
Log.i("Example", "the id is"+obj.getString("id"));
}

Categories

Resources