繁体   English   中英

在java中写一个json文件

[英]Write a json file in java

我想在java中编写一个json文件,但是它不起作用,我得到了这个警告:我想知道如何做到这一点,因为我要将一个标签的cfg文件转换为json。

Type safety: The method add(Object) belongs to the raw type ArrayList. References to generic type ArrayList<E> should be parameterized

我有这个代码:

package json;  

import java.io.File;  
import java.io.FileWriter;  
import java.io.IOException;  

import org.json.simple.JSONArray;  
import org.json.simple.JSONObject;

public class JsonWriter {  

    public static void main(String[] args) {  

        JSONObject countryObj = new JSONObject();  
        countryObj.put("Name", "India");  
        countryObj.put("Population", new Integer(1000000));  

        JSONArray listOfStates = new JSONArray();  
        listOfStates.add("Madhya Pradesh");  
        listOfStates.add("Maharastra");  
        listOfStates.add("Rajasthan");  

        countryObj.put("States", listOfStates);  

        try {  

            // Writing to a file  
            File file=new File("JsonFile.json");  
            file.createNewFile();  
            FileWriter fileWriter = new FileWriter(file);  
            System.out.println("Writing JSON object to file");  
            System.out.println("-----------------------");  
            System.out.print(countryObj);  

            fileWriter.write(countryObj.toJSONString());  
            fileWriter.flush();  
            fileWriter.close();  

        } catch (IOException e) {  
            e.printStackTrace();  
        }  

    }  
}  

我建议您只使用对象创建一个简单的ArrayList,然后使用序列化程序将它们序列化为JSON(在下面的示例中使用Jacksoin库)。 它看起来像这样:

首先,在类中定义您的模型(为了便于阅读而制作无包装):

public class Country{
  public String name;
  public Integer population;
  public List<String> states;
}

然后你可以继续创建它,并填充列表:

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonWriter {  

  public static void main(String[] args) {  

    Country countryObj = new Country();  
    countryObj.name = "India";
    countryObj.population = 1000000;

    List<String> listOfStates = new ArrayList<String>();  
    listOfStates.add("Madhya Pradesh");  
    listOfStates.add("Maharastra");  
    listOfStates.add("Rajasthan");  

    countryObj.states = listOfStates ;  
    ObjectMapper mapper = new ObjectMapper();

    try {  

        // Writing to a file   
        mapper.writeValue(new File("c:\\country.json"), countryObj );

    } catch (IOException e) {  
        e.printStackTrace();  
    }  

  }  
}

暂无
暂无

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

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