Pagini recente » Cod sursa (job #473280) | Cod sursa (job #2764381) | Cod sursa (job #1314889) | Cod sursa (job #537715) | Cod sursa (job #1343947)
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
class Main {
public static String buffer = "";
public static boolean parseKeyList = true;
public static PrintWriter writer;
public static void main(String[] args) throws FileNotFoundException {
String line;
writer = new PrintWriter("convertor.out");
try (BufferedReader br = new BufferedReader(new FileReader("convertor.in"))) {
while((line = br.readLine()) != null) {
parseString(line);
}
br.close();
} catch (Exception e) {
System.out.println("Something went wrong!");
System.out.println(e.toString());
}
writer.close();
}
public static void parseString(String line) {
buffer = buffer.concat(line);
while(containsJsonObject(buffer)) {
String jsonObject = buffer.substring(buffer.indexOf('{') + 1, buffer.indexOf('}'));
parseObject(jsonObject, parseKeyList);
buffer = buffer.substring(buffer.indexOf('}') + 1, buffer.length());
parseKeyList = false;
}
}
public static boolean containsJsonObject(String str) {
return (str.indexOf('{') != -1) && (str.indexOf('}') != -1);
}
public static void parseObject(String jsonObject, boolean parseKeyList) {
char ch;
StringBuilder csvLine = new StringBuilder();
StringBuilder csvHeader = new StringBuilder();
jsonObject = jsonObject.trim();
for(int i = 0; i < jsonObject.length(); i++) {
ch = jsonObject.charAt(i);
if(ch == '"') {
int valueSeparator = jsonObject.indexOf(':', i + 1),
nextQuote = jsonObject.indexOf('"', valueSeparator),
lastQuote = jsonObject.indexOf('"', nextQuote + 1),
nextComma = jsonObject.indexOf(',', valueSeparator);
// build key list
if(parseKeyList) {
int keyEndQuote = jsonObject.indexOf('"', i + 1);
csvHeader.append(jsonObject.substring(i + 1, keyEndQuote))
.append(",");
}
// build value list
if(nextComma == -1 || nextQuote == -1 || lastQuote == -1) { // end of object
csvLine.append(jsonObject.substring(valueSeparator + 1, jsonObject.length()).trim())
.append(",");
break;
} else if(nextComma > nextQuote && nextComma < lastQuote) { // comma in value
csvLine.append(jsonObject.substring(nextQuote + 1, lastQuote).trim())
.append(",");
// skip to next key
i = lastQuote;
} else if(nextComma > nextQuote && nextComma > lastQuote) { // string value
csvLine.append(jsonObject.substring(nextQuote + 1, lastQuote ).trim())
.append(",");
// skip to next key
i = nextComma;
} else { // numeric value
csvLine.append(jsonObject.substring(valueSeparator + 1, nextComma).trim())
.append(",");
i = nextComma;
}
}
}
if(parseKeyList) {
//System.out.println(csvHeader.toString());
writer.println(csvHeader.toString());
}
//System.out.println(csvLine.toString());
writer.println(csvLine.toString());
}
}