开发者

format json file with comma?

I have a json file.

{"bla":"bla"}
{"bla":"bla"}
{"bla":"bla"}
{"bla":"bla"}
......

How can I format these into a valid json type, like:

[    
    {"bla":"bla"},
    {"bla":"bla"},
    {"bla":"bla"},
    {"bla":"bla"},
    ......
    {"bla":"bla"}
]

Insert comma after each {} except las开发者_StackOverflow社区t one.

How can I do that in java?

Thanks.

PS: OK. This is a json file called "1.json" which I created from TCP response. I send some names to the server and I receive response and save as a file. Because all the data is like {"bal":"bla"}{"bal":"bla"}{"bal":"bla"}{"bal":"bla"}...... This is an invalid json structure that jQuery getJSON() couldn't read it. So I want to parse it to a valid type.


  1. Read the file line by line
  2. Use Gson to parse each JSON object in Java Object -- one by one, add it to a list
  3. Use Gson to convert the Java list in JSON array.

Look at Gson


How can I do that in java, thx!

Don't bother. Just open it in a text editor, do a search-replace between "} and "}, and a little clean up.


Using JSONObject.

//Java style pseudo-code (using some string reader)
JSONArray jsonArray = new JSONArray();  
while ((value = inputStream.readLine()) != null) { //This is Pseudocode - don't take is as Gospel
    JSONObject json = new JSONObject(value);
    jsonArray.put(json);
}

System.out.println(jsonArray.toString());


If you are just needing to reformat that input (lines of JSON objects, one line each), then you dont really need to convert them into Java JSON objects, you can just read the file in and convert it on the fly to the new JSON string:

StringBuilder str = new StringBuilder();
BufferedReader reader = null;
    try {
    str.append("[\n");

    for( String line = reader.readLine(); line != null; line = reader.readLine() ){
        str.append(line).append(",\n");
    }

    str.setLength(str.length()-2);
    str.append(']');

} catch( Exception ex ){
    if(reader != null){ reader.close(); }
}

or something similar. Just note that this will only work if your JSON objects are defined on single lines not spread across multiples.

Hope this helps.


String[] lines = inputJson.split('\n');
StringBuilder out = new StringBuilder();
out.append("[\n");
for (String line : lines) {
    out.append("    ").append(line).append(",\n");
}
out.setLength(out.length() - 2);
out.append("\n]");
String outputJson = out.toString();


// you can also make a JSON String without any kind of library cause using a library extends execution time of a program.

      String json = new String("[")
    while ((value = inputStream.readLine()) != null) { 
            if(json=="["){
             json +=value
            }else{
     json +=","+value
           }
       }

  //complete the last enclosing  character
  json +="]"  

this is a simple way I think

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜