我将WordPress自定义帖子类型作为JSON Feed传递给我的应用。
我创建了一个JSON页面模板,用于查询和显示结果,如下所示:
$directories [] = array(
'subtype' => 'mcms',
'type' => 'maps',
'summary' => get_the_title(),
'title' => get_the_title(),
'address' => get_field('address'),
'content' => get_the_content(),
'author' => get_the_author()
);
endwhile;
wp_reset_query();
echo json_encode ($directories);
这个输出是:
[
{
"subtype": "mcms",
"type": "maps",
"summary": "Directory Listing",
"title": "Directory Listing",
"address": false,
"content": "Lorem ipsum dolor sit amet",
"author": "admin"
}
]
我想按如下方式格式化输出:
"items:" [
{
"subtype": "mcms",
"type": "maps",
"summary": "Directory Listing",
"title": "Directory Listing",
"address": false,
"content": "Lorem ipsum dolor sit amet",
"author": "admin"
}
]
我正在尝试以下方法:
echo "items: ", json_encode ($directories);
但输出不是我需要的JSON格式
任何帮助?
答案 0 :(得分:0)
在致电$directories
之前,将json_encode
包裹在数组中。
$items = ['items' => $directories];
echo json_encode($items);
答案 1 :(得分:0)
在数组中添加目录是解决方案:
echo json_encode(array(' items' => $ directories));
答案 2 :(得分:0)
更改此行
$directories[] = array(...
到此
$directories['items'][] = array(...
你的回声就是这样的
echo json_encode($directories);
答案 3 :(得分:0)
您可以使输出像这样:
[
{
"items:" [
{
"subtype": "mcms",
"type": "maps",
"summary": "Directory Listing",
"title": "Directory Listing",
"address": false,
"content": "Lorem ipsum dolor sit amet",
"author": "admin"
}
]
}
]
您需要为项目创建一个对象,然后创建一个哈希图
Map<String, List<KeyValue>> map = new HashMap();
map.put("items", itemObject);
JsonBuilderFactory jsnFactory = Json.createBuilderFactory(null);
JsonObjectBuilder builder = jsnFactory.createObjectBuilder();
for (String key : map.keySet()) {
builder.add(keu,map.get(key));
}
return builder.build().toString();
返回