为什么不编写JSON?

时间:2018-08-24 12:11:54

标签: java json jackson

这是代码:

ol.geometry.point

这是我要创建的JSON:

@Override
        public void onPageSelected(int position) {
            mDrawerAdapter.setSelected(mItems[position]);
            mSnackBar.dismiss();
        }

但是当我执行代码时,这创建了一个空的JSON对象,为什么?

public static void init() { File file = new File(SimpleMessagesAPI.getMainAPI().getDataFolder(), "config.json"); try { ObjectMapper objectMapper = new ObjectMapper(); ArrayNode arrayNode = objectMapper.createArrayNode(); ObjectNode firstObjectNode = objectMapper.createObjectNode(); ObjectNode secondObjectNode = objectMapper.createObjectNode(); firstObjectNode.put("period", 5); firstObjectNode.put("async", true); firstObjectNode.put("country", "Europe/Bucharest"); secondObjectNode.putArray("broadcast") .add("&7Hello players! Now is %server_online players!") .add("&eNow is %time") .add("&6Thanks for playing on that server!") .add("&cHave fun guys! %motd"); ArrayNode firstArrayNode = objectMapper.createArrayNode(); firstArrayNode.add(firstObjectNode); ArrayNode secondArrayNode = objectMapper.createArrayNode(); secondArrayNode.add(secondObjectNode); ObjectNode principalObjectNode = objectMapper.createObjectNode(); principalObjectNode.putPOJO("mechanic", firstArrayNode); ObjectNode secondarObjectNode = objectMapper.createObjectNode(); secondarObjectNode.putPOJO("messages", secondArrayNode); arrayNode.add(principalObjectNode); arrayNode.add(secondarObjectNode); if (!file.exists()) { file.createNewFile(); objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayNode); } /*String json = file.toString(); JsonNode jsonNode = objectMapper.readTree(json); String messages = jsonNode.get("messages").asText(); String mechanic = jsonNode.get("mechanic").asText(); System.out.println("Messages: " + messages + "\n\n\n" + "Mechanic: " + mechanic + "\n\n");*/ //ObjectConfig config = new ObjectConfig(messages, mechanic); //objectMapper.writeValue(new File(SimpleMessagesAPI.getMainAPI().getDataFolder() + "config.json"), config); } catch (IOException e) { e.printStackTrace(); } } 说“结果被忽略”。

非常感谢帮助人员

2 个答案:

答案 0 :(得分:1)

我可以建议您从结构化数据创建json的更简单方法。您可以创建三个代表您的json结构的类。而且,您只需初始化对象实例并使用ObjectMapper对其进行序列化。

这是另一种方法:

package yourPackage;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.util.Arrays;
import java.util.List;

public class Test {
    public String serializeData() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();

        MyJson json = new MyJson();
        Mechanic mechanic = new Mechanic();
        mechanic.setAsync(true);
        mechanic.setCountry("Europe/Bucharest");
        mechanic.setPeriod(5);

        Message message = new Message();
        List<String> messages = Arrays.asList(
                "&7Hello players! Now is %server_online players!",
                "&eNow is %time",
                "&6Thanks for playing on that server!",
                "&cHave fun guys! %motd");

        message.setBroadcast(messages);

        json.setMechanic(mechanic);
        json.setMessages(message);

        return mapper.writeValueAsString(json);
    }
}

@Data // comes from lombok
class MyJson {
    private Mechanic mechanic;
    private Message messages;
}

@Data
class Mechanic{
    private int period;
    private boolean async;
    private String country;
}

@Data
class Message {
    private List<String> broadcast;
}

序列化输出:

{
    "mechanic": {
        "period": 5,
        "async": true,
        "country": "Europe/Bucharest"
    },
    "messages": {
        "broadcast": [
            "&7Hello players! Now is %server_online players!",
            "&eNow is %time",
            "&6Thanks for playing on that server!",
            "&cHave fun guys! %motd"
        ]
    }
}

您可以使用以下行写入目标文件:

    Files.write(Paths.get("config.json"), serializeData().getBytes());

龙目岛的Maven:

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>

答案 1 :(得分:1)

您的代码行有2个问题

file.createNewFile();
objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayNode);
  1. 您在file.createNewFile();上收到编译器警告,说 result被忽略,因为您忽略了由返回的布尔结果 file.createNewFile()

    您最好执行以下操作:

    if (!file.createNewFile())
        throw new IOException("could not create file " + file);
    
  2. 您的方法调用.writeValueAsString(arrayNode)仅 产生JSON字符串,但不会将此字符串写入任何地方。

    您需要改用.writeValue(file, arrayNode)