-8

I have a json file which is somthing like

{ "44451":["67","188","188E","188R","982E","301"]}

How do I read the strings inside of "44451" and display it in a StringBuilder in android studio?

Help would be appreciated. Thanks.

Amila
  • 5,195
  • 1
  • 27
  • 46
Kyreus
  • 1
  • 2
  • You probably want to parse the json with something like JsonReader (http://developer.android.com/reference/android/util/JsonReader.html), this should then provide you with the facilities to traverse the Json structure to extract the data you want. I expect your question is receiving downvotes, because you should already be able to find alot of information online about working with Json on android/java. – Robadob Oct 01 '15 at 09:01
  • See this for some guidance: http://stackoverflow.com/questions/9605913/how-to-parse-json-in-android – Mattias Lindberg Oct 01 '15 at 09:03
  • @Robadob I actually got a very good idea about how it works, but when I was debugging the program, it gave me this error ' cannot find local var i ) in the for loop, so i was wondering if i was doing something wrong in the code. Hence this question again to check if i was going in the right direction. – Kyreus Oct 01 '15 at 12:30

3 Answers3

1
JSONObject json = new JSONObject(jsonString);
JSONArray jArray = json.getJSONArray("44451");


StringBuilder sb;
for(int i=0; i<jArray.length(); i++){
sb.append(jArray.getJSONObject(i).toString());
}
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37
  • when I do this, Android studio gives me an error saying it cant find local variable i. how should I deal with this? – Kyreus Oct 01 '15 at 09:09
1

Don't really understand the StringBuilder aspect, but if you want to read the whole text from the JSON, then you can do this.

the whole text is an Object Because it surrounded with { }, the you have an key 44451 assign to an array ["67",...].

to read this, you will read the object first then read the content of the array.

JSONObject object = new JSONObject('');
JSONArray array = object.getJSONArray("44451");
for (int i = 0; i < array.length(); i++) { 
 String value = array[i];
 // other opetations as desired..
}
Ibukun Muyide
  • 1,294
  • 1
  • 15
  • 23
0

I would recommend to use FasterXML Jackson library because you can parse JSON into arbitrary user defined types. You could add it a gradle dependency like this

compile 'com.fasterxml.jackson.core:jackson-databind:2.6.2'
compile 'com.fasterxml.jackson.core:jackson-core:2.6.2'

Then you can parse your JSON like this.

String json = "{ \"44451\":[\"67\",\"188\",\"188E\",\"188R\",\"982E\",\"301\"]}";

ObjectMapper mapper = new ObjectMapper();
Map<String, List<String>> values = mapper.readValue(json, new TypeReference<Map<String, List<String>>>() {
});

StringBuilder str = new StringBuilder();
for (String value : values.get("44451")) {
    // do whatever you want 
}
schrieveslaach
  • 1,689
  • 1
  • 15
  • 32