当前位置: 首页 > 面试题库 >

尝试使用Java解析JSON字符串时发生错误

宋弘壮
2023-03-14
问题内容

我正在尝试使用java解析JSON字符串。我不知道该怎么做,我在互联网上搜索了很多内容,但有了一些主意。有了我,我有构建代码,但它不起作用。当尝试执行我的代码时,它将引发错误。我无法解决错误。

看到下面是我的代码:

import java.util.*;
import java.io.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JSOnNStringParsing {

    public static void main(String[] args) {        
        try
        {
            BufferedReader read=new BufferedReader(new FileReader("D:\\Kavi works\\OutputFiles\\JSON_String.txt"));
            String line=read.readLine();
            while(line!=null)
            {
                System.out.println("Line = "+line);
                JSONParser jsonParser = new JSONParser();
                JSONObject jsonObject = (JSONObject) jsonParser.parse(line);
                System.out.println("Read : "+jsonObject.get("read"));
                JSONArray network = (JSONArray) jsonObject.get("network");
                Iterator<String> iterator = network.iterator();
                while (iterator.hasNext()) {
                    System.out.println(iterator.next());
                }
            }
        }
        catch(Exception e)
        {
            System.out.println("Error occured :"+e);
        }
    }
}

我的JSON字符串在该文件中:

{"read":"2015-05-07T19:30:48.165009273+05:30","network":{"rx_bytes":11124,"rx_packets":116,"rx_errors":0,"rx_dropped":0,"tx_bytes":648,"tx_packets":8,"tx_errors":0,"tx_dropped":0},"cpu_stats":{"cpu_usage":{"total_usage":157158138204,"percpu_usage":[157158138204],"usage_in_kernelmode":49530000000,"usage_in_usermode":58420000000},"system_cpu_usage":258964110000000,"throttling_data":{"periods":0,"throttled_periods":0,"throttled_time":0}},"memory_stats":{"usage":73969664,"max_usage":74600448,"stats":{"active_anon":73928704,"active_file":4096,"cache":86016,"hierarchical_memory_limit":18446744073709551615,"inactive_anon":4096,"inactive_file":32768,"mapped_file":32768,"pgfault":62880,"pgmajfault":0,"pgpgin":34656,"pgpgout":34482,"rss":73883648,"rss_huge":67108864,"total_active_anon":73928704,"total_active_file":4096,"total_cache":86016,"total_inactive_anon":4096,"total_inactive_file":32768,"total_mapped_file":32768,"total_pgfault":62880,"total_pgmajfault":0,"total_pgpgin":34656,"total_pgpgout":34482,"total_rss":73883648,"total_rss_huge":67108864,"total_unevictable":0,"total_writeback":0,"unevictable":0,"writeback":0},"failcnt":0,"limit":2099310592},"blkio_stats":{"io_service_bytes_recursive":[],"io_serviced_recursive":[],"io_queue_recursive":[],"io_service_time_recursive":[],"io_wait_time_recursive":[],"io_merged_recursive":[],"io_time_recursive":[],"sectors_recursive":[]}}

当我执行代码时,它会引发如下错误:

Line = {"read":"2015-05-07T19:30:48.165009273+05:30","network":{"rx_bytes":11124,"rx_packets":116,"rx_errors":0,"rx_dropped":0,"tx_bytes":648,"tx_packets":8,"tx_errors":0,"tx_dropped":0},"cpu_stats":{"cpu_usage":{"total_usage":157158138204,"percpu_usage":[157158138204],"usage_in_kernelmode":49530000000,"usage_in_usermode":58420000000},"system_cpu_usage":258964110000000,"throttling_data":{"periods":0,"throttled_periods":0,"throttled_time":0}},"memory_stats":{"usage":73969664,"max_usage":74600448,"stats":{"active_anon":73928704,"active_file":4096,"cache":86016,"hierarchical_memory_limit":18446744073709551615,"inactive_anon":4096,"inactive_file":32768,"mapped_file":32768,"pgfault":62880,"pgmajfault":0,"pgpgin":34656,"pgpgout":34482,"rss":73883648,"rss_huge":67108864,"total_active_anon":73928704,"total_active_file":4096,"total_cache":86016,"total_inactive_anon":4096,"total_inactive_file":32768,"total_mapped_file":32768,"total_pgfault":62880,"total_pgmajfault":0,"total_pgpgin":34656,"total_pgpgout":34482,"total_rss":73883648,"total_rss_huge":67108864,"total_unevictable":0,"total_writeback":0,"unevictable":0,"writeback":0},"failcnt":0,"limit":2099310592},"blkio_stats":{"io_service_bytes_recursive":[],"io_serviced_recursive":[],"io_queue_recursive":[],"io_service_time_recursive":[],"io_wait_time_recursive":[],"io_merged_recursive":[],"io_time_recursive":[],"sectors_recursive":[]}}
Error occured :java.lang.NumberFormatException: For input string: "18446744073709551615"

请帮助我解决这个问题,在此先感谢


问题答案:

您的json在Java中解析错误。在Java中,最大值Long9223372036854775807
,但在json中,您已经超过了它。Json可以访问非常长的数字,但是Java无法访问。

之后就可以将json中的数字类型更改为String了。看下面的例子。

{
  "read": "2015-05-07T19:30:48.165009273+05:30",
  "network": {
    "rx_bytes": 11124,
    "rx_packets": 116,
    "rx_errors": 0,
    "rx_dropped": 0,
    "tx_bytes": 648,
    "tx_packets": 8,
    "tx_errors": 0,
    "tx_dropped": 0
  },
  "cpu_stats": {
    "cpu_usage": {
      "total_usage": 157158138204,
      "percpu_usage": [
        157158138204
      ],
      "usage_in_kernelmode": 49530000000,
      "usage_in_usermode": 58420000000
    },
    "system_cpu_usage": 258964110000000,
    "throttling_data": {
      "periods": 0,
      "throttled_periods": 0,
      "throttled_time": 0
    }
  },
  "memory_stats": {
    "usage": 73969664,
    "max_usage": 74600448,
    "stats": {
      "active_anon": 73928704,
      "active_file": 4096,
      "cache": 86016,
      "hierarchical_memory_limit": "18446744073709552000898498494949849849849849849849849849841998498498484984",
      "inactive_anon": 4096,
      "inactive_file": 32768,
      "mapped_file": 32768,
      "pgfault": 62880,
      "pgmajfault": 0,
      "pgpgin": 34656,
      "pgpgout": 34482,
      "rss": 73883648,
      "rss_huge": 67108864,
      "total_active_anon": 73928704,
      "total_active_file": 4096,
      "total_cache": 86016,
      "total_inactive_anon": 4096,
      "total_inactive_file": 32768,
      "total_mapped_file": 32768,
      "total_pgfault": 62880,
      "total_pgmajfault": 0,
      "total_pgpgin": 34656,
      "total_pgpgout": 34482,
      "total_rss": 73883648,
      "total_rss_huge": 67108864,
      "total_unevictable": 0,
      "total_writeback": 0,
      "unevictable": 0,
      "writeback": 0
    },
    "failcnt": 0,
    "limit": 2099310592
  },
  "blkio_stats": {
    "io_service_bytes_recursive": [],
    "io_serviced_recursive": [],
    "io_queue_recursive": [],
    "io_service_time_recursive": [],
    "io_wait_time_recursive": [],
    "io_merged_recursive": [],
    "io_time_recursive": [],
    "sectors_recursive": []
  }
}

编辑: 在我意识到@Jon
Skeet的评论之后,他对Json简单是正确的。在其他json解析器中,您可以轻松解析json,它将作为进行处理BigInteger。BigInteger没有限制。

这是一个例子:

try{
            String line = "{'read':'2015-05-07T19:30:48.165009273+05:30','network':{'rx_bytes':11124,'rx_packets':116,'rx_errors':0,'rx_dropped':0,'tx_bytes':648,'tx_packets':8,'tx_errors':0,'tx_dropped':0},'cpu_stats':{'cpu_usage':{'total_usage':157158138204,'percpu_usage':[157158138204],'usage_in_kernelmode':49530000000,'usage_in_usermode':58420000000},'system_cpu_usage':258964110000000,'throttling_data':{'periods':0,'throttled_periods':0,'throttled_time':0}},'memory_stats':{'usage':73969664,'max_usage':74600448,'stats':{'active_anon':73928704,'active_file':4096,'cache':86016,'hierarchical_memory_limit':18446744073709552000,'inactive_anon':4096,'inactive_file':32768,'mapped_file':32768,'pgfault':62880,'pgmajfault':0,'pgpgin':34656,'pgpgout':34482,'rss':73883648,'rss_huge':67108864,'total_active_anon':73928704,'total_active_file':4096,'total_cache':86016,'total_inactive_anon':4096,'total_inactive_file':32768,'total_mapped_file':32768,'total_pgfault':62880,'total_pgmajfault':0,'total_pgpgin':34656,'total_pgpgout':34482,'total_rss':73883648,'total_rss_huge':67108864,'total_unevictable':0,'total_writeback':0,'unevictable':0,'writeback':0},'failcnt':0,'limit':2099310592},'blkio_stats':{'io_service_bytes_recursive':[],'io_serviced_recursive':[],'io_queue_recursive':[],'io_service_time_recursive':[],'io_wait_time_recursive':[],'io_merged_recursive':[],'io_time_recursive':[],'sectors_recursive':[]}}";
            line = line.replaceAll( "'", "\"" );
            while( line != null ){

                JsonObject asJsonObject = new JsonParser().parse( line ).getAsJsonObject().get( "network" ).getAsJsonObject();
                Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();

                for( Entry<String, JsonElement> entry : entrySet ){
                    System.out.println( entry.getKey() + " : " + entry.getValue() );
                }
            }
        }
        catch( Exception e ){
            System.out.println( "Error occured :" + e );
        }

我用gson解析了您的json。谢谢@Jon Skeet。



 类似资料:
  • 问题内容: 我很难解析/格式化从Web服务接收回的Date字符串。我尝试了多种方法,但是没有运气。 样本日期字符串: 例外: 样例代码: 我发现,如果删除日期和时间之间的“ T”并将其替换为空格,则格式正确。有人有什么建议吗? -更新- 在深入研究API文档之后,我发现了这一点: 所有响应DateTime值均采用UTC格式。 您需要应用UTC偏移量来计算本地显示时间。 DateTime是以下列格式

  • 问题内容: 我正在尝试解析java中的JSON字符串,以单独打印各个值。但是,在使程序运行时,出现以下错误- 我的班级看起来像- 让我知道我丢失了什么,或者为什么每次运行该应用程序时都会得到该错误。任何意见,将不胜感激。 问题答案: 看我的评论。当以 android.jar身份运行时,您需要包含完整的org.json库。仅包含要针对其进行编译的存根。 __ 此外,您还必须在JSON数据中删除额外的

  • 我正在创建一个android应用程序,它以json格式显示从在线API获取的天气数据。为此,我使用的是格森图书馆。 我有以下JSON字符串,我从一个map对象中获得: 它包含以下值: 但是,当我尝试使用该字符串创建另一个贴图对象时,我遇到了一个异常。 异常logcat报告: 通用域名格式。谷歌。格森。JsonSyntaxException:com。谷歌。格森。流动MalformedJsonExce

  • 问题内容: 我正在尝试解析一个JSON结构,如: 也就是说,JSON中的元素是带有转义json的字符串。 所以,我有一些类似的东西 但这崩溃了 这是因为.c的输出是字符串,而不是JSON。如何让jq解析此字符串? 我最初的解决方案是使用sed将替换所有的逃生字符(,和),但凌乱的,我认为有内置的方式做到这一点? 谢谢! 编辑:另外,这里可用的jq版本是: 我想我可以根据需要更新它。 问题答案: j

  • 问题内容: 我在C#中有一个类似以下的字符串。我需要遍历并创建HTML表输出。我尝试使用JSON.NET,但无法弄清楚如何检索键(名称,年龄和工作)。 表格格式为 任何帮助将不胜感激。 Dave提供的代码在这里是理想的解决方案..但是它适用于.NET 4.0 ..我已经将JSON.NET和以下代码用于.NET 3.5 使用Newtonsoft.Json.Linq; 问题答案: 您可以使用.NET

  • 我得到的回应是: {“response”:{“id”:“R1”,“cmd”:[{“batchSize”:50,“startRow”:0,“name”:“doLogin”,“result”:“OK”,“attributes”:[{“name”:“businessName”,“type”:“String”},{“name”:“objId”,“type”:“Long”},{“name”;“type”;“