我有一个包含冒号分隔数据的文本文件。我如何将其转换为JSON对象?我在文件中有以下文字:
<Access-Control-Allow-Headers>
答案 0 :(得分:0)
下面的代码是在java中。根据您的要求,您可能需要进行一些更改。
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
readFile();
}
public static void readFile() throws IOException {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream("d:/input.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fileInputStream));
String line = null;
String obj = new String("[");
while ((line = br.readLine()) != null) {
if (line.split(":").length > 1) {
Entry entry = new Entry(line.split(":")[0], line.split(":")[1]);
obj = obj +" \n "+ entry.toString();
}
}
obj = obj.replaceAll("\"BEGIN\":\"VCARD\"", "{");
obj = obj.replaceAll("\"END\":\"VCARD\"", "},");
obj = obj.substring(0, obj.lastIndexOf(","));
obj = obj + "\n]";
System.out.println(obj);
br.close();
} catch ( Exception e) {
System.out.println(e);
} finally {
fileInputStream.close();
}
}
}
class Entry {
private String key;
private String value;
Entry (String key, String value) {
this.key = key;
this.value = value;
}
@Override
public String toString() {
return "\""+ key + "\"" + ":" + "\"" + value + "\"";
}
}
输出类似于json格式。
[
{
"VERSION":"2.1"
"FN":"Campus Police"
"N":"Campus Police"
"TEL":"555-EDU-HELP"
"ADR":"8230 Boone Blvd.;Bldg 001;;Vienna;VA;22181;"
"X-MS-OL-DEFAULT-POSTAL-ADDRESS":"01155"
"EMAIL":"police@wisconsin.edu"
"REV":"20120501T180000Z"
},
{
"VERSION":"2.1"
"FN":"Campus Medical Clinic"
"N":"Campus Medical Clinic"
"TEL":"555-EDU-HURT"
"ADR":"8230 Boone Blvd.;Bldg 001;;Vienna;VA;22181;"
"X-MS-OL-DEFAULT-POSTAL-ADDRESS":"01155"
"EMAIL":"medical@wisconsin.edu"
"REV":"20120501T180000Z"
}
]