添加引号将JSON转换为POJO

dxpyg8gm  于 2023-04-13  发布在  其他
关注(0)|答案(2)|浏览(142)

我想使用http://www.jsonschema2pojo.org/将我的JSON响应转换为Java,但我正在查看的JSON没有引号,因此我无法使用此网站。如何生成带引号的JSON以利用此网站?

5sxhfpxr

5sxhfpxr1#

这对我很有效:

public class addQuotes{
    String dir = "enter file location here";
    File quotes = new File(dir);

private String readFile(){
    String q = "";

    try(FileInputStream fin = new FileInputStream(dir)){
        int s = (int) quotes.length();
        byte[] r = new byte[s];
        fin.read(r);
        q = new String(r);

    }catch(Exception e){
        e.printStackTrace();
    }
    return q;
}

private void writeFile(FileOutputStream fos, String output) throws IOException{
    byte[] data = output.getBytes();
    fos.write(data);
}

public addQuotes() {
    String add = readFile().replaceAll("(\\w+)", "\"$1\"");
    try{
        FileOutputStream fos =  new FileOutputStream(dir);
        writeFile(fos, add);
    }catch(Exception e){
        e.printStackTrace();
    }
  }
}
ppcbkaq5

ppcbkaq52#

被接受的解决方案不能正确处理包含连字符和/或空格的值。以下是我的看法:

String json = json.replaceAll(", ", ",");
    int n = json.length();
    StringBuilder result = new StringBuilder();
    for(int i=0; i<n; i++){
        char c = json.charAt(i);
        if(c == ':'){
            // add closing quote for key; 
            result.append("\":");
            if(json.charAt(i+1) != '{' && json.charAt(i+1) != '[')// add opening quote for value 
                result.append("\"");
            if(json.charAt(i+1) == '}' || json.charAt(i+1) == ']' || json.charAt(i+1) == ',')// value empty
                result.append("\"");
            continue;
        }
        
        if(c == '{' || c == '[' && (json.charAt(i+1) != '{' && json.charAt(i+1) != '[')){
            // add opening bracket and then opening quote for key
            result.append(c); 
            result.append("\"");
        }
        else if(i < n-1 && (json.charAt(i+1) == ',' || json.charAt(i+1) == ']' || json.charAt(i+1) == '}') && c != ']' && c != '}'){
            // add closing quote for value
            result.append(c); 
            result.append("\"");
        }
        else if(c == ',' && json.charAt(i+1) != '{' && json.charAt(i+1) != '[')
            result.append(",\"");
        else result.append(c); 
        
        
    }

相关问题