Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-9557

This commit is contained in:
amit2103 2018-10-27 22:06:53 +05:30
commit a9e385a53d
2 changed files with 65 additions and 0 deletions

View File

@ -0,0 +1,30 @@
package com.baeldung.jsonjava;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.json.JSONArray;
import org.json.JSONObject;
public class JSONArrayGetValueByKey {
public List<String> getValuesByKeyInJSONArray(String jsonArrayStr, String key) {
List<String> values = new ArrayList<>();
JSONArray jsonArray = new JSONArray(jsonArrayStr);
for (int idx = 0; idx < jsonArray.length(); idx++) {
JSONObject jsonObj = jsonArray.getJSONObject(idx);
values.add(jsonObj.optString(key));
}
return values;
}
public List<String> getValuesByKeyInJSONArrayUsingJava8(String jsonArrayStr, String key) {
JSONArray jsonArray = new JSONArray(jsonArrayStr);
return IntStream.range(0, jsonArray.length())
.mapToObj(index -> ((JSONObject) jsonArray.get(index)).optString(key))
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.jsonjava;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
public class JSONArrayGetValueByKeyUnitTest {
private static final JSONArrayGetValueByKey obj = new JSONArrayGetValueByKey();
@Test
public void givenJSONArrayAndAKey_thenReturnAllValuesForGivenKey() {
String jsonStr = "[" + " {" + " \"name\": \"John\"," + " \"city\": \"chicago\"," + " \"age\": \"22\" " + "}," + " { " + "\"name\": \"Gary\"," + " \"city\": \"florida\"," + " \"age\": \"35\" " + "}," + " { " + "\"name\": \"Selena\","
+ " \"city\": \"vegas\"," + " \"age\": \"18\" " + "} " + "]";
List<String> actualValues = obj.getValuesByKeyInJSONArray(jsonStr, "name");
assertThat(actualValues, equalTo(Arrays.asList("John", "Gary", "Selena")));
}
@Test
public void givenJSONArrayAndAKey_whenUsingJava8Syntax_thenReturnAllValuesForGivenKey() {
String jsonStr = "[" + " {" + " \"name\": \"John\"," + " \"city\": \"chicago\"," + " \"age\": \"22\" " + "}," + " { " + "\"name\": \"Gary\"," + " \"city\": \"florida\"," + " \"age\": \"35\" " + "}," + " { " + "\"name\": \"Selena\","
+ " \"city\": \"vegas\"," + " \"age\": \"18\" " + "} " + "]";
List<String> actualValues = obj.getValuesByKeyInJSONArrayUsingJava8(jsonStr, "name");
assertThat(actualValues, equalTo(Arrays.asList("John", "Gary", "Selena")));
}
}