Created
April 26, 2014 06:35
-
-
Save swankjesse/11313308 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.squareup.okhttp.sample; | |
import com.google.gson.Gson; | |
import com.google.gson.GsonBuilder; | |
import com.google.gson.JsonArray; | |
import com.google.gson.JsonElement; | |
import com.google.gson.JsonObject; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.io.OutputStreamWriter; | |
import java.io.Reader; | |
import java.io.Writer; | |
import java.util.Map; | |
public class JsonRewriter { | |
public static void main(String[] args) throws Exception { | |
String file = "..."; | |
InputStream in = new FileInputStream(file); | |
Reader reader = new InputStreamReader(in, "utf-8"); | |
Gson gson = new GsonBuilder() | |
.setPrettyPrinting() | |
.disableHtmlEscaping() | |
.create(); | |
JsonElement jsonElement = gson.fromJson(reader, JsonElement.class); | |
jsonElement = transform("", jsonElement); | |
Writer writer = new OutputStreamWriter(new FileOutputStream(file + "2"), "utf-8"); | |
gson.toJson(jsonElement, writer); | |
writer.close(); | |
} | |
private static JsonElement transform(String path, JsonElement jsonElement) { | |
if (jsonElement instanceof JsonObject) { | |
JsonObject object = (JsonObject) jsonElement; | |
JsonObject result = new JsonObject(); | |
for (Map.Entry<String, JsonElement> entry : object.entrySet()) { | |
result.add(entry.getKey(), transform(path + "." + entry.getKey(), entry.getValue())); | |
} | |
return result; | |
} else if (jsonElement instanceof JsonArray) { | |
JsonArray result = new JsonArray(); | |
JsonArray array = (JsonArray) jsonElement; | |
for (int i = 0; i < array.size(); i++) { | |
result.add(transform(path + "[" + i + "]", array.get(i))); | |
} | |
return result; | |
} else { | |
System.out.println(path + ": " + jsonElement); | |
return jsonElement; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment