帮我写一个工具类, 使用java代码 把json转换为 php的array, 并对array进行格式化
时间: 2024-02-24 15:58:03 浏览: 64
好的,以下是一个简单的Java工具类,可以将JSON字符串转换为PHP数组,并对数组进行格式化:
```java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class JsonToPhpArray {
public static String jsonToPhpArray(String json) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(json);
return elementToPhpArray(je);
}
private static String elementToPhpArray(JsonElement element) {
if (element.isJsonObject()) {
Map<String, Object> map = new LinkedHashMap<>();
element.getAsJsonObject().entrySet().forEach(entry -> {
map.put(entry.getKey(), elementToPhpArray(entry.getValue()));
});
return mapToPhpArray(map);
} else if (element.isJsonArray()) {
List<Object> list = new ArrayList<>();
element.getAsJsonArray().forEach(item -> {
list.add(elementToPhpArray(item));
});
return listToPhpArray(list);
} else if (element.isJsonPrimitive()) {
return "\"" + element.getAsString() + "\"";
} else {
return "null";
}
}
private static String mapToPhpArray(Map<String, Object> map) {
StringBuilder sb = new StringBuilder("array(\n");
map.entrySet().forEach(entry -> {
sb.append(" ").append("\"").append(entry.getKey()).append("\" => ").append(entry.getValue()).append(",\n");
});
sb.append(")");
return sb.toString();
}
private static String listToPhpArray(List<Object> list) {
StringBuilder sb = new StringBuilder("array(\n");
list.forEach(item -> {
sb.append(" ").append(item).append(",\n");
});
sb.append(")");
return sb.toString();
}
}
```
使用方法:
```java
String json = "{\"name\": \"John\", \"age\": 30, \"cars\": [\"Ford\", \"BMW\", \"Fiat\"]}";
String phpArray = JsonToPhpArray.jsonToPhpArray(json);
System.out.println(phpArray);
```
输出结果:
```
array(
"name" => "John",
"age" => "30",
"cars" => array(
"Ford",
"BMW",
"Fiat",
),
)
```
阅读全文