2

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?

SmashCode
  • 4,227
  • 8
  • 38
  • 56
  • 1
    I'm a little confused. Is the WCF returning a string formatted as a JSON array or an actual array of strings? If it's an array why don't you just iterate through each *array element*, strip out the index and run a JSON deserializing function on the resulting string? – Spencer Ruport Apr 13 '12 at 20:39

4 Answers4

8

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);
}
Mahdi Hijazi
  • 4,424
  • 3
  • 24
  • 29
  • Yeah, this is it, shortly after posting this I realized I made this more difficult than it needed to be. – SmashCode Apr 13 '12 at 21:03
0

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));
        }
    }
Community
  • 1
  • 1
Rob Angelier
  • 2,335
  • 16
  • 29
  • Not really, I've had to do something similar to what you posted in other Android projects, but that was dealing with JSONArrays that contained objects. If the data being returned was the format ["Name" : "the_name", ... ] I'd be fine, but if you look at the data being returned, your code wouldn't work. – SmashCode Apr 13 '12 at 20:35
  • Thats true, the post below could be more what your looking for. – Rob Angelier Apr 13 '12 at 20:43
0

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

Spencer Ruport
  • 34,865
  • 12
  • 85
  • 147
0

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.

Atul
  • 3,043
  • 27
  • 39