在Spring

时间:2015-07-23 05:27:40

标签: java json spring rest

我目前正在以

的方式使用内容
"potter",["potter harry","potter","potter hallows 2","potter collection","potter hallows 1","potter dvd box","potter 7","potter hallows","potter blue ray","potter feniks"],[{"xcats":[{"name":"dvd_all"},{"name":"books_nl"}]},{},{},{},{},{},{},{},{},{}],[]]

在Spring中使用以下代码

RestTemplate restTemplate = new RestTemplate();
String information = restTemplate.getForObject(URL, String.class);
//further parsing of information, using String utilities

显然这不是要走的路,因为我应该能够以某种方式自动解析它。我也只需要第二个元素的内容(数组,从potter harrypotter feniks)。

当它的json内容不是名称值时,解析GET响应的最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

@Test
public  void testJson(){
    RestTemplate template = new RestTemplate();
    ResponseEntity<ArrayNode> entity = template.
            exchange("https://api.myjson.com/bins/2rl7m", HttpMethod.GET, null, new ParameterizedTypeReference<ArrayNode>() {
            });

    ArrayNode body = entity.getBody();
    body.get(1).forEach(m->{
        System.out.println(m.asText());});
}

但我的建议是,如果你可以改变响应类型不是json数组中的混合值类型会更好

答案 1 :(得分:0)

以下帮助程序类使我能够轻松解析响应并获取我需要的列表

public class JSONHelper {

private static final JsonFactory factory = new JsonFactory();

private static final ObjectMapper mapper = new ObjectMapper(factory);

public static List<String> getListOnPosition(int i, String inputWithFullList) throws JsonProcessingException, IOException {
    List<String> result = new ArrayList<String>();
    JsonNode rootNode = mapper.readTree(inputWithFullList);
    ArrayNode node = (ArrayNode) rootNode.get(i);
    if (!node.isArray()) {
        result.add(node.asText());
    } else {
        for (final JsonNode subNode : node) {
            result.add(subNode.asText());
        }
    }
    return result;
}

}

针对此场景的一些JUnit测试

public class JSONHelperTest {
@Test
public void parseListOnPositionFullListTest() throws JsonProcessingException, IOException {
    String inputWithFullList = "[\"a\",[\"b\", \"c\", \"d\"],[],[]]";
    List<String> result = JSONHelper.getListOnPosition(1, inputWithFullList);
    assertEquals(3, result.size());
    assertEquals(Arrays.asList("b", "c", "d"), result);
}

@Test
public void parseListOnPositionOneElementListTest() throws JsonProcessingException, IOException {
    String inputWithFullList = "[\"a\",[\"b\"],[],[]]";
    List<String> result = JSONHelper.getListOnPosition(1, inputWithFullList);
    assertEquals(1, result.size());
    assertEquals(Arrays.asList("b"), result);
}

@Test
public void parseListOnPositionEmptyListTest()  throws JsonProcessingException, IOException {
    String inputWithFullList = "[\"a\",[],[],[]]";
    assertTrue(JSONHelper.getListOnPosition(1, inputWithFullList).isEmpty());
}
}