我们需要从以下API http://www.viralheat.com/developer/sentiment_api#method1获取信息,这些信息可以将输出抛出到xml或json中。我应该使用什么java api,以便我可以编写一个包装器来解析可能由UI以JSON格式和XML格式的独立客户端使用的信息。
答案 0 :(得分:2)
我会使用支持XML和JSon的Xstream来映射数据结构。
答案 1 :(得分:2)
注意:我是 EclipseLink JAXB (MOXy) 负责人,也是JAXB 2(JSR-222)专家组的成员。
您可以使用MOXy执行此操作,请查看我的博客文章,其中一个带有一组元数据的域模型与Google Maps Geocoding API V2的JSON和XML格式一起使用:
<强>地址强>
以下是示例中的一个类。除JAXB注释外,它还利用MOXy's @XmlPath
extension:
package blog.geocode.json;
import javax.xml.bind.annotation.XmlType;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlType(propOrder={"country", "state", "city", "street", "postalCode"})
public class Address {
@XmlPath("Placemark/ns:AddressDetails/ns:Country/ns:AdministrativeArea/ns:Locality/ns:Thoroughfare/ns:ThoroughfareName/text()")
private String street;
@XmlPath("Placemark/ns:AddressDetails/ns:Country/ns:AdministrativeArea/ns:Locality/ns:LocalityName/text()")
private String city;
@XmlPath("Placemark/ns:AddressDetails/ns:Country/ns:AdministrativeArea/ns:AdministrativeAreaName/text()")
private String state;
@XmlPath("Placemark/ns:AddressDetails/ns:Country/ns:CountryNameCode/text()")
private String country;
@XmlPath("Placemark/ns:AddressDetails/ns:Country/ns:AdministrativeArea/ns:Locality/ns:PostalCode/ns:PostalCodeNumber/text()")
private String postalCode;
}
<强>演示强>
标准JAXB API用于与JSON和XML进行转换:
package blog.geocode.json;
import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Address.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// XML
XMLInputFactory xif = XMLInputFactory.newFactory();
StreamSource xml = new StreamSource("http://maps.google.com/maps/geo?q=1600+Amphitheatre+Parkway,+Mountain+View,+CA&output=xml&sensor=false&key=YOUR_KEY_HERE");
XMLStreamReader xsr = xif.createXMLStreamReader(xml);
xsr.nextTag(); // Advance to kml tag
xsr.nextTag(); // Advance to Response tag
JAXBElement<Address> addressFromXML = unmarshaller.unmarshal(xsr, Address.class);
marshaller.marshal(addressFromXML, System.out);
// JSON
unmarshaller.setProperty("eclipselink.media.type", "application/json");
StreamSource json = new StreamSource("http://maps.google.com/maps/geo?q=1600+Amphitheatre+Parkway,+Mountain+View,+CA&output=json&sensor=false&key=YOUR_KEY_HERE");
JAXBElement<Address> addressFromJSON = unmarshaller.unmarshal(json, Address.class);
marshaller.setProperty("eclipselink.media.type", "application/json");
marshaller.marshal(addressFromJSON, System.out);
}
}
答案 2 :(得分:1)
我建议使用Jackson,因为它在生成JSON和XML时优于其他推荐的替代方案:
我认为您绝对不能使用单个库或框架,如果您只是为每个库选择最佳选择,结果通常会更好。例如,XStream适用于XML,但会生成丑陋的JSON(并且会慢慢生成)。 由于格式阻抗,从XML到JSON很容易出错,我还没有看到一个XML处理库,它可以有效地生成JSON clean JSON(甚至只是干净或有效)。