解析一个字符串对象为 JSONObject。

huangapple go评论73阅读模式
英文:

parse a string object to a JSONObject

问题

我需要解析一个包含JSON文件数据的字符串,将其解析为JSONObject,并迭代其内容以获取键和值,以便进行进一步处理。我在将文件内容转换为字符串后解析文件内容时遇到困难。我尝试使用parse()和quote(),但似乎我漏掉了一些细节,我犯了一个重大错误。

这是我处理的JSON文件片段:

{
    {
        "id": 0,
        "name": "project1",
        "couverage": "100",
        "completness": "44.8",
        "consistency": "46",
    }
    
    {
        "id": 1,
        "name": "project2",
        "couverage": "100",
        "completness": "44.8",
        "consistency": "46",
    }
    
    {
        "id": 2,
        "name": "project3",
        "couverage": "100",
        "completness": "44.8",
        "consistency": "46",
    }
}

这是我编写的代码:

public void readfromJsonFile(File jsonFile, long readTimeStamp) {
    logger.info("从JSON文件读取:{}", jsonFile.getName());
    
    try {
        // 读取文件内容
        String content = new String(Files.readAllBytes(jsonFile.toPath()));
        
        JSONParser jsonParser = new JSONParser(content);
        JSONObject obj = (JSONObject) jsonParser.parse();
        JSONArray key = obj.names();
        
        for (int i = 0; i < key.length(); ++i) {
            String keys = key.getString(i);
            System.out.println(keys);
            String value = obj.getString(keys);
            System.out.println(value);
        }
    } catch (Exception e) {
        logger.error("解析JSON文件失败:{}", jsonFile.getName());
    }
}
英文:

I need to parse a string that contains data of JSON file into a JSONObject and iterate over it's content to get it's keys and values for further treatement after. I'am stuck at parsing the content of a file after transforming it to a string. I tried to user parse() , quote() but it seems i'am missing a detail and i'am making a major mistake.

This is a snippet of the json file i treat :

{
    {
	&quot;id&quot;:0,
	&quot;name&quot;: &quot;project1&quot;,
    &quot;couverage&quot;: &quot;100&quot;,
	&quot;completness&quot;: &quot;44.8&quot;,
	&quot;consistency&quot;: &quot;46&quot;,
	}
	
	{
	&quot;id&quot;:1,
	&quot;name&quot;: &quot;project2&quot;,
    &quot;couverage&quot;: &quot;100&quot;,
	&quot;completness&quot;: &quot;44.8&quot;,
	&quot;consistency&quot;: &quot;46&quot;,
	}
	
	{
	&quot;id&quot;:2,
	&quot;name&quot;: &quot;project3&quot;,
    &quot;couverage&quot;: &quot;100&quot;,
	&quot;completness&quot;: &quot;44.8&quot;,
	&quot;consistency&quot;: &quot;46&quot;,
	}
}

and this is the code i developed

public void readfromJsonFile(File jsonFile, long readTimeStamp) {
	logger.info(&quot;Read from JSON file:  {}&quot;, jsonFile.getName());
	
	try{
	    	
	    //Read File Content
	    String content = new String(Files.readAllBytes(jsonFile.toPath()));
	    
        JSONParser jsonParser = new JSONParser(content);
		JSONObject obj = (JSONObject) jsonParser.parse();
		JSONArray key = obj.names();
		
        for (int i = 0; i &lt; key.length (); ++i) {
		    String keys = key.getString(i);
		    System.out.println(keys);
		    String value = obj.getString (keys);
		    System.out.println(value);
    }catch (Exception e) {
			logger.error(&quot;Failed to parse JSON File: {}&quot;, jsonFile.getName());
	    }
}

答案1

得分: 1

你也可以使用Jackson Databind。

创建一个POJO类,例如:

public class POJO {

   private int id;
   private String name;
   private String couverage;
   private String completness;
   private String consistency;

   // 获取器、设置器和构造函数

}

修改文件中的JSON:

[
    {
    "id":0,
    "name": "project1",
    "couverage": "100",
    "completness": "44.8",
    "consistency": "46"
    },
    {
    "id":1,
    "name": "project2",
    "couverage": "100",
    "completness": "44.8",
    "consistency": "46"
    },
    {
    "id":2,
    "name": "project3",
    "couverage": "100",
    "completness": "44.8",
    "consistency": "46"
    }
]

代码:

public void readfromJsonFile(File jsonFile, long readTimeStamp) {
    logger.info("从JSON文件读取:  {}", jsonFile.getName());
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        POJO[] pojos = objectMapper.readValue(jsonFile, POJO[].class);
        for (int i = 0; i < pojos.length; ++i) {
            System.out.println(pojos[i].getId());
        }
    } catch (Exception e) {
        logger.error("解析JSON文件失败: {}", jsonFile.getName());
    }
}
英文:

You can use Jackson Databind as well.

Create a POJO class. For example :

public class POJO {

   private int id;
   private String name;
   private String couverage;
   private String completness;
   private String consistency;

   // getters, setters and constructors

}

Modify the JSON in the file.

[
    {
    &quot;id&quot;:0,
    &quot;name&quot;: &quot;project1&quot;,
    &quot;couverage&quot;: &quot;100&quot;,
    &quot;completness&quot;: &quot;44.8&quot;,
    &quot;consistency&quot;: &quot;46&quot;
    },
    {
    &quot;id&quot;:1,
    &quot;name&quot;: &quot;project2&quot;,
    &quot;couverage&quot;: &quot;100&quot;,
    &quot;completness&quot;: &quot;44.8&quot;,
    &quot;consistency&quot;: &quot;46&quot;
    },
    {
    &quot;id&quot;:2,
    &quot;name&quot;: &quot;project3&quot;,
    &quot;couverage&quot;: &quot;100&quot;,
    &quot;completness&quot;: &quot;44.8&quot;,
    &quot;consistency&quot;: &quot;46&quot;
    }
]

Code :

public void readfromJsonFile(File jsonFile, long readTimeStamp) {
    logger.info(&quot;Read from JSON file:  {}&quot;, jsonFile.getName());
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        POJO[] pojos = objectMapper.readValue(jsonFile, POJO[].class);
        for (int i = 0; i &lt; pojos.length; ++i) {
            System.out.println(pojos[i].getId());
        }
    } catch (Exception e) {
            logger.error(&quot;Failed to parse JSON File: {}&quot;, jsonFile.getName());
    }
}

答案2

得分: 0

尝试像这样操作:

JSONArray array_ = new JSONArray(content);
JSONObject obj = (JSONObject) array_.get(0); // 或任何索引

然后您可以使用该对象。

英文:

Try it like this

JSONArray array_= new JSONArray(content);
JSONObject obj = (JSONObject) array_.get(0);// or any index

then you can use the Object.

huangapple
  • 本文由 发表于 2020年9月16日 23:08:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63922968.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定