java 替换 JSON 键中的空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30228343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace whitespace in JSON keys
提问by gnanagurus
I am thinking of a best solution to replace all the whitespaces in JSON keys with underscore.
我正在考虑用下划线替换 JSON 键中的所有空格的最佳解决方案。
{
"Format": "JSON",
"TestData": {
"Key with Spaces in it": {
"And Again": {
"Child_Key1": "Financial",
"Child_Key2": null
},
.........
.....
I want the above to be converted as shown below:
我希望将上述内容转换为如下所示:
{
"Format": "JSON",
"TestData": {
"Key_with_Spaces_in_it": {
"And_Again": {
"Child_Key1": "Financial",
"Child_Key2": null
},
.........
.....
Any suggestions ?
有什么建议 ?
Does any Java library have any predefined function to do this ?
是否有任何 Java 库有任何预定义的函数来执行此操作?
回答by grill
Replacing Keys
更换钥匙
The following code uses Google's JSON parser to extract keys, reformat them, and then create a new JSON object:
以下代码使用 Google 的 JSON 解析器来提取密钥,重新格式化它们,然后创建一个新的 JSON 对象:
public static void main(String[] args) {
String testJSON = "{\"TestKey\": \"TEST\", \"Test spaces\": { \"child spaces 1\": \"child value 1\", \"child spaces 2\": \"child value 2\" } }";
Map oldJSONObject = new Gson().fromJson(testJSON, Map.class);
JsonObject newJSONObject = iterateJSON(oldJSONObject);
Gson someGson = new Gson();
String outputJson = someGson.toJson(newJSONObject);
System.out.println(outputJson);
}
private static JsonObject iterateJSON(Map JSONData) {
JsonObject newJSONObject = new JsonObject();
Set jsonKeys = JSONData.keySet();
Iterator<?> keys = jsonKeys.iterator();
while(keys.hasNext()) {
String currentKey = (String) keys.next();
String newKey = currentKey.replaceAll(" ", "_");
if (JSONData.get(currentKey) instanceof Map) {
JsonObject currentValue = iterateJSON((Map) JSONData.get(currentKey));
newJSONObject.add(currentKey, currentValue);
} else {
String currentValue = (String) JSONData.get(currentKey);
newJSONObject.addProperty(newKey, currentValue);
}
}
return newJSONObject;
}
You can read more about GSON here.
您可以在此处阅读有关 GSON 的更多信息。
Replacing Values
替换值
Depending on how your JSON data is set up, you might need to switch JSONArray with JSONObject.
根据 JSON 数据的设置方式,您可能需要将 JSONArray 与 JSONObject 切换。
JSONArrays begin and end with []
, while JSONObjects begin and end with {}
JSONArrays 开始和结束[]
,而 JSONObjects 开始和结束{}
In short, these methods will travel over an entire array/object and replace any spaces with underscores. They're recursive, so they will dive into child JSONArrays/JSONObjects.
简而言之,这些方法将遍历整个数组/对象并用下划线替换任何空格。它们是递归的,因此它们将深入研究子 JSONArrays/JSONObjects。
If the JSON data is encoded as a Java JSONArray, you can do the following:
如果 JSON 数据被编码为 Java JSONArray,您可以执行以下操作:
public static void removeJSONSpaces(JSONArray theJSON) {
for (int i = 0; while i < theJSON.length(); i++) {
if (theJSON.get(i) instanceof JSONArray) {
currentJSONArray = theJSON.getJSONArray(i);
removeJSONSpaces(currentJSONArray);
} else {
currentEntry = theJSON.getString(i);
fixedEntry = currentEntry.replace(" ", "_");
currentJSONArray.put(i, fixedEntry);
}
}
}
In short, this method will travel over an entire array and replace any spaces with underscores. It's recursive, so it will dive into child JSONArrays.
简而言之,此方法将遍历整个数组并用下划线替换任何空格。它是递归的,所以它会深入到子 JSONArrays 中。
You can read more about JSONArrays here
您可以在此处阅读有关 JSONArrays 的更多信息
If the data is encoded as a JSONObject, you'd want to do something like:
如果数据被编码为一个 JSONObject,你会想要做这样的事情:
public static void removeJSONSpaces(JSONObject theJSON) {
jObject = new JSONObject(theJSON.trim());
Iterator<?> keys = jObject.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
if (jObject.get(key) instanceof JSONObject) {
removeJSONSpaces(jObject.get(key))
} else {
currentEntry = theJSON.getString(i);
fixedEntry = currentEntry.replace(" ", "_");
currentJSONArray.put(i, fixedEntry);
}
}
}
You can read more about JSONObjects here
您可以在此处阅读有关 JSONObjects 的更多信息
回答by BlackHatSamurai
You can just read in each of the keys/values then use the String replace(String oldString, String newString)
method.
您可以读取每个键/值,然后使用该String replace(String oldString, String newString)
方法。
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(char,%20char)
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(char,%20char)
回答by alexopoulos7
I am using gson library in order to remove bad keys from json string because I want to create the AVRO file of the json. Keys with spaces or non Alphanumeric are not acceptable from Avro so I have to sanitize input first.
我正在使用 gson 库来从 json 字符串中删除坏键,因为我想创建 json 的 AVRO 文件。Avro 不接受带有空格或非字母数字的键,因此我必须先清理输入。
The above snippet removes whitespaces and character $ from all keys (iterative). I assume my json string is JsonObject.
上面的代码段从所有键(迭代)中删除了空格和字符 $。我假设我的 json 字符串是 JsonObject。
Check out a small sample code that I have used.
查看我使用过的一个小示例代码。
for (String json: allJsons){
JsonObject schema = new JsonParser().parse(json).getAsJsonObject();
JsonObject cleanSchema = new JsonObject();
Set<Map.Entry<String, JsonElement>> entries = schema.entrySet();
for (Map.Entry<String, JsonElement> entry: entries) {
String key = entry.getKey().replace("$","").replace(" ","");
JsonElement value = entry.getValue();
if (value.isJsonObject()){
JsonObject subValue = new JsonObject();
Set <Map.Entry<String, JsonElement>> subEntries = ((JsonObject) value).entrySet();
for (Map.Entry<String, JsonElement> subEntry: subEntries) {
String subKey = subEntry.getKey().replace("$","").replace(" ","");
subValue.add(subKey, subEntry.getValue());
}
value = subValue;
}
cleanSchema.add(key, value);
}
System.out.println("Clean schema "+cleanSchema.toString());
byte[] bytes = converter.convertToAvro(cleanSchema.toString().getBytes(), avroSchema);
String avroFile = outputFileName+"_"+counter+".avsc";
Files.write(Paths.get(avroFile), bytes);
counter++;
System.out.println("Avro File Created "+avroFile);
}
回答by Mamun Kayum
Try this one:
试试这个:
String testJSON = "{\"menu\": {\n" +
" \"id no\": \"file\",\n" +
" \"value type\": \"File\",\n" +
" \"popup value\": {\n" +
" \"menu item\": [\n" +
" {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},\n" +
" {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},\n" +
" {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}\n" +
" ]\n" +
" }\n" +
"}}";
JSONObject json = new JSONObject(testJSON);
System.out.println("Final output: "+replaceKeyWhiteSpace(json));
replace the WhiteSpace with "_"
用“_”替换空格
private static JSONObject replaceKeyWhiteSpace(Object json) {
JSONObject jsonObject = null;
if (json instanceof JSONObject) {
jsonObject = (JSONObject) json;
List<String> keyList = new LinkedList<String>(jsonObject.keySet());
for (String key : keyList) {
if (!key.matches(".*[\s\t\n]+.*")) {
Object value = jsonObject.get(key);
replaceKeyWhiteSpace(value);
continue;
}
Object value = jsonObject.remove(key);
String newKey = key.replaceAll("[\s\t\n]", "_");
replaceKeyWhiteSpace(value);
jsonObject.accumulate(newKey, value);
}
} else if (json instanceof JSONArray) {
for (Object aJsonArray : (JSONArray) json) {
replaceKeyWhiteSpace(aJsonArray);
}
}
return jsonObject;
}
}
回答by Lalji Gajera
This is what I did to remove white space from Json Keys. Solution will work for JsonArray and JsonObject, just printing matching regex keys with white space and replace those keys. Live Demo : online Java compiler
这就是我从 Json Keys 中删除空格的方法。解决方案适用于 JsonArray 和 JsonObject,只需打印带有空格的匹配正则表达式键并替换这些键。现场演示:在线 Java 编译器
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class MatcherGroupExample {
public static void main(String[] args) {
String text = "{\"co nf ig\": {\"oauthSecret\": [{\"i d\": 45,\"config123\": {\"oauthSecret\": \"P8n2x5Ht0nFRRB0A\",\"status\": \"CREATED\"},\"SERVER132\": \"1000\"},{\"id\": 46,\"config123\": {\"oauthSecret\": \"wP8n2x5Ht0nFRRB0A\",\"status\": \"CREATED\"},\"SERVER132\": \"1000\"}],\"oauthKey\": \"newtest\",\"SERV ER\": \"1000\"},\"feat ures\": [ 9004, 9005] ,\"d\":\"dd\"}";
String patternString1 = "\"([^\"]+?[ ]+[^\"]+?)\"\s*:";
Pattern pattern = Pattern.compile(patternString1);
Matcher matcher = pattern.matcher(text);
while(matcher.find()) {
System.out.println("found: " + matcher.group(1));
text= text.replaceAll("\""+matcher.group(1)+"\"","\""+(matcher.group(1).replaceAll(" ",""))+"\"");
}
System.out.println("Final output:"+text);
}
}
回答by candy.cloud.nimbus
Remove only the white space on the strings in jason code not all white space on jason code
仅删除 jason 代码中字符串上的空格,而不是 jason 代码中的所有空格
public String removeWhiwspaceInJasonString(String jsonStr) {
boolean changeActive = false;
String output = '';
for(int i=0; i<jsonStr; i++){
if(jsonStr.charAt(i) == '"')
changeActive =!changeActive;
else if(changeActive)
if(jsonStr.charAt(i) == ' ')
output += '_';
else
output += jsonStr.charAt(i);
else
output += jsonStr.charAt(i);
}
return output;
}