{
"buildingNumber": 123,
"apatmentNumber": "4567",
"apartments": "123",
"isActive": true,
"possibleActions": [
"ENTER",
"EXIT"
],
"enterVia": {
"J1-B1": [
"DEFAULT_ROUTE"
],
"A1-D1": [
"DEFAULT_ROUTE"
]
},
"SectionMap": {},
"route": "abc|def (via xyz)"
}
我有以上示例JSON。 “enterVia”中的整个内容是动态的。 我必须从响应中读取这个嵌套的Json(如下所示)并在另一个请求中发送它。
{
"J1-B1": [
"DEFAULT_ROUTE"
],
"A1-D1": [
"DEFAULT_ROUTE"
]
}
如果可以使用Gson,ObjectMapper,请建议一种方式。
答案 0 :(得分:0)
我找到了一个使用ObjectMapper的解决方案。以下是代码:
import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonParseTest {
public static void main(String[] args) {
String json = "{\r\n\t\"J1-B1\": [\r\n\t\t\"DEFAULT_ROUTE\"\r\n\t],\r\n\t\"A1-D1\": [\r\n\t\t\"DEFAULT_ROUTE\"\r\n\t]\r\n}";
ObjectMapper objectMapper = new ObjectMapper();
Map<String, List<String>> routesMap = null;
try {
routesMap = objectMapper.readValue(json, new TypeReference<Map<String, List<String>>>(){});
} catch (JsonParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JsonMappingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("read response output: " +routesMap);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
String jsonRequest = null;
try {
jsonRequest = objectMapper.writeValueAsString(routesMap);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("next request output: " +jsonRequest);
}
}
计划的输出:
读取响应输出:{J1-B1 = [DEFAULT_ROUTE],A1-D1 = [DEFAULT_ROUTE]}
下一个请求输出:{&#34; J1-B1&#34;:[&#34; DEFAULT_ROUTE&#34;],&#34; A1-D1&#34;:[&#34; DEFAULT_ROUTE&#34; ]}