简体   繁体   English

从Java访问JSON字符串中的长值

[英]Access to a long value in a JSON string from Java

I want to get the value of the long "transmitBytes" in this JSON string 我想获取此JSON字符串中长“ transferBytes”的值

[

    {
       "portNumber" : 2,

       "queueId" : 0,

       "transmitBytes" : 1944145,

       "transmitPackets" : 1684,

       "transmitErrors" : 0
    }

]

I have used the org.json library and implemented the code: 我使用了org.json库并实现了代码:

    String queueJson = [{"portNumber":2,"queueId":0,"transmitBytes":1944145,"transmitPackets":1684,"transmitErrors":0}];

    System.out.println("The JSON string is: " + queueJson);


     JSONObject obj; 

     try { 
     obj = new JSONObject(queueJson); 
     long TXbytes =  obj.getLong("transmitBytes");
     System.out.println("The amount of transmittet bytes is " + TXbytes);
     } catch (JSONException e) { 
             // TODO Auto-generated catch block
     e.printStackTrace(); 
     }

The issue occurs, when I'm running the Apache tomcat web server. 当我运行Apache tomcat Web服务器时,会发生此问题。 Following error occurs: 发生以下错误:

SEVERE: A child container failed during start

with following: 具有以下内容:

org.apache.catalina.LifecycleException: Failed to start component

When I remove the JSONObject class and the corresponding org.json library, everything works fine, and the server runs without any issues. 当我删除JSONObject类和相应的org.json库时,一切正常,服务器运行没有任何问题。 Does anyone know why this issue occurs, and are there another libraries available to access a long value in a JSON string from Java ?. 有谁知道为什么会发生此问题,是否还有其他库可用于从Java访问JSON字符串中的长值?

Thanks in advance 提前致谢

Your JSON form is: 您的JSON形式为:

Array -> Object(s)

So you should first access array and then object 因此,您应该先访问数组,然后再访问对象

JSONArray array = new JSONArray(queueJson);
JSONObject obj = array.getJSONObject(0);

0 because it's the first index (the only one). 0,因为它是第一个索引(唯一的索引)。 The other code will be the same. 其他代码将相同。

Another way is to fix your problem by editing your Json (if it's made by you) and make it return something like this: 另一种方法是通过编辑Json(如果由您自己制作)来解决问题,并使其返回类似以下内容的内容:

{
    "portNumber": 2,
    "queueId": 0,
    "transmitBytes": 1944145,
    "transmitPackets": 1684,
    "transmitErrors": 0
}

try this code: 试试这个代码:

JSonArray array=new JSonArray(queueJson);

instead of obj = new JSONObject(queueJson); 而不是obj = new JSONObject(queueJson);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM