1 2 3 4 5 | @Provider @Produces(value = { “application/json_dojo_tree”}) public class JsonDojoTreeProvider implements MessageBody-Writer<DojoTree> { ... } |
1 2 3 4 | public boolean isWriteable(Class<?> inputClass, Type type, Annotation[] annotations, MediaType mediaType) { return inputClass == == DojoTree.class; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | public void writeTo(DojoTree list, Class<?> inputClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> map, OutputStream os) throws IOException, WebApplicationException { JAXBContext jc; final String methodName = “writeTo”; try { JAXBContext jc = JAXBContext.newInstance("rest.resource"); OutputStream tempOs = new ByteArrayOutputStream(); Marshaller ms = jc.createMarshaller(); HashMap<String, String> namespaceMap = new HashMap<String, String>(); namespaceMap.put("http://www.w3.org/2001/XMLSchema-instance", "xmlns"); namespaceMap.put("http://www.w3.org/2001/XMLSchema-instance", "xmlns.type"); XMLOutputFactory factory = new MappedXMLOutputFactory(namespaceMap); XMLStreamWriter xsw = factory.createXMLStreamWriter(tempOs); ms.marshal(list, xsw); String replacedJsonString = replaceAll(tempOs.toString()); // remove dojoItems tag int index = replacedJsonString.indexOf(":"); int end = replacedJsonString.lastIndexOf("}"); // For an empty list items tag won't be present, But Dojo //client requires it if (replacedJsonString.indexOf("items") > 0) { if (index > 0) { if (list.getItems().size() == 1) { String itemsString = replacedJsonString.substring(index + 1, end); os.write(replaceWithParenthesisForSingleItem(itemsString).getBytes()); } else { os.write(replacedJsonString.substring(index + 1, end).getBytes()); } } else { os.write(replacedJsonString.getBytes()); } } else { String emptJsonString = "{items:[],startRecordIndex:" + "0" + ", endRecordIndex:" + "0" + ",totalRecords:" + "0" + "}"; os.write(emptJsonString.getBytes()); } os.close(); xsw.close(); tempOs.close(); } catch (JAXBException e) { e.printStackTrace(); } catch (XMLStreamException e) { e.printStackTrace(); } } private String replaceWithParenthesisForSingleItem(String jsonString) { int firstColonIndex = jsonString.indexOf(“:”); int firstFlowerBracketIndex = jsonString.indexOf(“}”); String jsonObject = jsonString.substring(firstColonIndex + 1, firstFlowerBracketIndex + 1); |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |