Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用抛弃的JSON解析_Java_Json_Jettison - Fatal编程技术网

Java 使用抛弃的JSON解析

Java 使用抛弃的JSON解析,java,json,jettison,Java,Json,Jettison,我正在尝试使用抛弃来解析JSON对象。 这就是我正在使用的代码 String s ="{\"appUsage\":[{\"appName\":\"ANDROID\",\"totalUsers\":\"0\"},{\"appName\":\"IOS\",\"totalUsers\":\"4\"}]}"; JSONObject obj = new JSONObject(s); ArrayList<MiAppUsage> l1 = (ArrayList<MiAppUsage&g

我正在尝试使用抛弃来解析JSON对象。 这就是我正在使用的代码

String s ="{\"appUsage\":[{\"appName\":\"ANDROID\",\"totalUsers\":\"0\"},{\"appName\":\"IOS\",\"totalUsers\":\"4\"}]}";

JSONObject obj = new JSONObject(s);

ArrayList<MiAppUsage> l1 =  (ArrayList<MiAppUsage>) jsonParser(ArrayList.class, obj);

public static Object jsonParser(Class c, JSONObject obj)
            throws JSONException, XMLStreamException, JAXBException {
        JAXBContext jc = JAXBContext.newInstance(c);
        Configuration config = new Configuration();
        MappedNamespaceConvention con = new MappedNamespaceConvention(config);
        XMLStreamReader xmlStreamReader = new MappedXMLStreamReader(obj, con);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        ArrayList<MiAppUsage>customer = (ArrayList<MiAppUsage>) unmarshaller.unmarshal(xmlStreamReader);
        return customer;
    }
String s=“{\'appUsage\':[{\'appName\':\'ANDROID\',\'totalUsers\':\'0\',{\'appName\':\'IOS\',\'totalUsers\':\'4\'}”;
JSONObject obj=新的JSONObject;
ArrayList l1=(ArrayList)jsonParser(ArrayList.class,obj);
公共静态对象jsonParser(c类,JSONObject obj)
抛出JSONException、XMLStreamException、JAXBEException{
JAXBContext jc=JAXBContext.newInstance(c);
配置配置=新配置();
MappedNamespaceConvention con=新的MappedNamespaceConvention(配置);
XMLStreamReader XMLStreamReader=新的MappedXMLStreamReader(obj,con);
Unmarshaller Unmarshaller=jc.createUnmarshaller();
ArrayListcustomer=(ArrayList)unmarshaller.unmarshal(xmlStreamReader);
退货客户;
}
我犯了这个错误

线程“main”javax.xml.bind.UnmarshaleException中出现异常 -链接异常:[javax.xml.bind.UnmarshaleException:意外元素(uri:,local:“appUsage”)。预期元素为 (无)] com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(未知 来源)在 com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(未知 来源)在 com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(未知 源代码)位于com.json.UnmarshalDemo.jsonParser(UnmarshalDemo.java:56) 在com.json.UnmarshalDemo.main(UnmarshalDemo.java:33)上,由以下原因引起: javax.xml.bind.UnmarshaleException:意外元素(uri:“”), 本地:“应用程序使用”)。预期的元素至少为(无) com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(未知 来源)在 com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(未知 来源)在 com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(未知 来源)在 com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(未知 来源)在 com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(未知 来源)在 com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.\u startElement(未知 来源)在 com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(未知 来源)在 com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(未知 来源)在 com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector.handlestarelement(未知 来源)在 com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(未知 来源)。。。4更多原因:javax.xml.bind.UnmarshalException: 意外元素(uri:,本地:“appUsage”)。预期的要素是 (没有)。。。14多


如何解决此问题

注意:我是专家组的负责人和成员

如果您最终正在寻找一种使用JAXB(JSR-222)实现与JSON交互的方法,那么下面是如何使用MOXy实现的。抛弃是一个有趣的库,但使用它时会遇到一些问题:

演示

仅使用标准的JavaSEAPI。需要在
解组器
上设置两个特定于MOXy的属性:
“eclipselink.media type”
指定
“application/json”
,以及
“eclipselink.json.include root”
指示没有根节点

package forum9924567;

import java.io.StringReader;
import java.util.ArrayList;

import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;

public class Demo {

    private static final String s ="{\"appUsage\":[{\"appName\":\"ANDROID\",\"totalUsers\":\"0\"},{\"appName\":\"IOS\",\"totalUsers\":\"4\"}]}";

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setProperty("eclipselink.media-type", "application/json");
        unmarshaller.setProperty("eclipselink.json.include-root", false);
        StreamSource json = new StreamSource(new StringReader(s));
        Root root = unmarshaller.unmarshal(json, Root.class).getValue();

        ArrayList<MiAppUsage> customer = root.appUsage;
        for(MiAppUsage miAppUsage : customer) {
            System.out.print(miAppUsage.appName);
            System.out.print(' ');
            System.out.println(miAppUsage.totalUsers);
        }
    }

}
MiAppUsage

package forum9924567;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class MiAppUsage {

    String appName;
    int totalUsers;

}
jaxb.properties

要将MOXy指定为JAXB提供程序,您需要在与域类相同的包中添加一个名为
java.properties
的文件,其中包含以下条目:

javax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory
输出

以下是运行演示代码的输出:

ANDROID 0
IOS 4
了解更多信息


    • 我认为这不能用抛弃来完成。似乎
      JSONObject
      不喜欢将数组作为其值的根元素。如果这是一个选项,您可以将输入更改为JSON数组,该数组可以通过抛弃进行解析:

      public static void main(String[] args) throws Exception {
        String s ="[{\"appUsage\":{\"appName\":\"ANDROID\",\"totalUsers\":\"0\"}},{\"appUsage\":{\"appName\":\"IOS\",\"totalUsers\":\"4\"}}]";
      
        JSONArray arr = new JSONArray(s);
      
        List<MiAppUsage> list = unmarshal(MiAppUsage.class, arr);
        for(MiAppUsage miAppUsage : list) {
          System.out.println(miAppUsage.appName + ": " + miAppUsage.totalUsers);
        }
      }
      
      public static <T> List<T> unmarshal(Class<T> cls, JSONArray arr) throws JSONException, XMLStreamException, JAXBException {
        List<T> list = new ArrayList<T>();
        for (int i = 0; i < arr.length(); i++) {
          list.add(unmarshal(cls, arr.getJSONObject(i)));
        }
        return list;
      }
      
      public static <T> T unmarshal(Class<T> cls, JSONObject obj) throws JSONException, XMLStreamException, JAXBException {
        JAXBContext jc = JAXBContext.newInstance(cls);
        Configuration config = new Configuration();
        MappedNamespaceConvention con = new MappedNamespaceConvention(config);
        XMLStreamReader xmlStreamReader = new MappedXMLStreamReader(obj, con);
      
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        return cls.cast(unmarshaller.unmarshal(xmlStreamReader));
      }
      
      JAXB注释模型类如下所示:

      import javax.xml.bind.annotation.*;
      
      @XmlRootElement(name = "appUsage")
      @XmlAccessorType(XmlAccessType.FIELD)
      public class MiAppUsage {
        String appName;
        int totalUsers;
      }
      
      作为抛弃的替代方案,您的原始JSON输入可以使用的
      JsonXMLMapper
      轻松解析,它可以与任何JAXB实现一起工作:

      String s ="{\"appUsage\":[{\"appName\":\"ANDROID\",\"totalUsers\":\"0\"},{\"appName\":\"IOS\",\"totalUsers\":\"4\"}]}";
      
      JsonXMLMapper<MiAppUsage> mapper = new JsonXMLMapper<MiAppUsage>(MiAppUsage.class);
      List<MiAppUsage> list = mapper.readArray(new StringReader(s));
      
      for(MiAppUsage miAppUsage : list) {
        System.out.println(miAppUsage.appName + ": " + miAppUsage.totalUsers);
      }
      
      String s=“{\'appUsage\':[{\'appName\':\'ANDROID\',\'totalUsers\':\'0\',{\'appName\':\'IOS\',\'totalUsers\':\'4\'}”;
      JsonXMLMapper-mapper=新的JsonXMLMapper(MiAppUsage.class);
      List List=mapper.readArray(新的StringReader);
      用于(MiAppUsage MiAppUsage:list){
      System.out.println(miAppUsage.appName+“:”+miAppUsage.totalUsers);
      }
      

      有关StAXON的JAXB支持的更多信息,请参阅wiki页面。

      用 @XmlRootElement(name=“appUsage”,namespace=”“)

      例如: @XmlRootElement(name=“appUsage”,namespace=”“) 公共类MiAppUsage{


      }

      回到OP的原始问题,我们如何使用抛弃来解决这个问题?回到OP的原始问题,我们如何使用抛弃来解决这个问题?这里,抛弃似乎有一个问题。我编辑了我的答案,并添加了一个解决方案,其中使用了一个稍微修改过的输入?
      import javax.xml.bind.annotation.*;
      
      @XmlRootElement(name = "appUsage")
      @XmlAccessorType(XmlAccessType.FIELD)
      public class MiAppUsage {
        String appName;
        int totalUsers;
      }
      
      String s ="{\"appUsage\":[{\"appName\":\"ANDROID\",\"totalUsers\":\"0\"},{\"appName\":\"IOS\",\"totalUsers\":\"4\"}]}";
      
      JsonXMLMapper<MiAppUsage> mapper = new JsonXMLMapper<MiAppUsage>(MiAppUsage.class);
      List<MiAppUsage> list = mapper.readArray(new StringReader(s));
      
      for(MiAppUsage miAppUsage : list) {
        System.out.println(miAppUsage.appName + ": " + miAppUsage.totalUsers);
      }