帮我写一个工具类, 使用java代码 把json转换为 php的array
时间: 2024-02-24 08:56:47 浏览: 72
好的,以下是一个简单的工具类,可以将 JSON 转换为 PHP 数组:
```java
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonToPhpArrayConverter {
public static String convert(JSONObject json) {
StringBuilder builder = new StringBuilder();
builder.append("array(");
convertJsonToPhpArray(json, builder);
builder.append(")");
return builder.toString();
}
private static void convertJsonToPhpArray(JSONObject json, StringBuilder builder) {
for (String key : json.keySet()) {
Object value = json.get(key);
builder.append("'").append(key).append("' => ");
if (value instanceof JSONObject) {
builder.append("array(");
convertJsonToPhpArray((JSONObject) value, builder);
builder.append(")");
} else if (value instanceof JSONArray) {
builder.append("array(");
convertJsonArrayToPhpArray((JSONArray) value, builder);
builder.append(")");
} else {
builder.append("'").append(value).append("'");
}
builder.append(",");
}
builder.deleteCharAt(builder.length() - 1);
}
private static void convertJsonArrayToPhpArray(JSONArray jsonArray, StringBuilder builder) {
for (int i = 0; i < jsonArray.length(); i++) {
Object value = jsonArray.get(i);
if (value instanceof JSONObject) {
builder.append("array(");
convertJsonToPhpArray((JSONObject) value, builder);
builder.append(")");
} else if (value instanceof JSONArray) {
builder.append("array(");
convertJsonArrayToPhpArray((JSONArray) value, builder);
builder.append(")");
} else {
builder.append("'").append(value).append("'");
}
builder.append(",");
}
builder.deleteCharAt(builder.length() - 1);
}
}
```
使用方法如下:
```java
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
JSONObject json = new JSONObject("{\"name\":\"John\",\"age\":30,\"cars\":[{\"name\":\"BMW\",\"models\":[\"320\",\"X3\",\"X5\"]},{\"name\":\"Ford\",\"models\":[\"Fiesta\",\"Focus\",\"Mustang\"]}]}");
String phpArray = JsonToPhpArrayConverter.convert(json);
System.out.println(phpArray);
}
}
```
输出结果如下:
```
array('name' => 'John','age' => 30,'cars' => array('0' => array('name' => 'BMW','models' => array('0' => '320','1' => 'X3','2' => 'X5',)),'1' => array('name' => 'Ford','models' => array('0' => 'Fiesta','1' => 'Focus','2' => 'Mustang',)),))
```
阅读全文