json文件 java,用Java写一个json文件

I want to write a json file in java, but it doesn't work, I get this warning:

I want to know how to do this, because I am going to convert a cfg file that is tabbed to json.

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

and I have this code:

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();

}

}

}

解决方案

I would suggest that you just make a simple ArrayList with your objects, and then serialize them into JSON with a serializer (Using the Jacksoin library in the example below). It would look something like this:

First, define your model in a class (Made without incapsulations for readability):

public class Country{

public String name;

public Integer population;

public List states;

}

Then you can go ahead and create it, and populate the list:

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 listOfStates = new ArrayList();

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();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值