[英]How to add a variable JSON root during run-time in Jackson
现在,我想有几个带有属性值的单词,例如“Happy”、“Mad”等,但我不知道是哪个。 我想将数据记录到 JSON 文件中,但是使用 @JsonRootName 不起作用,因为注释不接受变量。
有没有办法这样做?
目前我有以下几点:
/**
* @author VeeAyeInIn
*
* Words will be valued on a scale of [-1.0, 1.0] representing whether they count towards a specific emotion, or
* against it. The farther towards 1.0 the score goes, the more weight for the emotion exists, whilst the farther
* it goes to -1.0, is more weight against the emotion. 0 has no weight, and will essentially just add more overall
* weight towards the sentence as a whole, but does not effect the score.
*/
public static class ValuedWord {
/*
* This uses 7 scores for a word, based off of the Chinese text, "Book of Rites," which mentioned seven 'feelings
* of men.' These will be the 'primary' emotions, whilst more complex ones will be based off of the scores of
* these seven.
*/
public double joy;
public double anger;
public double sadness;
public double fear;
public double love;
public double disliking;
public double liking;
/*
* How many times it has been used, to prevent dramatic jumps in calculation, larger uses will cause a smaller
* change in scores. Eventually it will settle out into a logarithmic curve-like format.
*/
public long uses;
/**
* Default constructor for reading JSON values.
*/
public ValuedWord() {}
/**
* Create a valued word from predefined values.
*
* @param joy Score [-1.0, 1.0] for joy
* @param anger Score [-1.0, 1.0] for anger
* @param sadness Score [-1.0, 1.0] for sadness
* @param fear Score [-1.0, 1.0] for fear
* @param love Score [-1.0, 1.0] for love
* @param disliking Score [-1.0, 1.0] for disliking
* @param liking Score [-1.0, 1.0] for liking
* @param uses How many times the word has been updated
*/
public ValuedWord(double joy, double anger, double sadness, double fear, double love, double disliking, double liking, long uses) {
this.joy = joy;
this.anger = anger;
this.sadness = sadness;
this.fear = fear;
this.love = love;
this.disliking = disliking;
this.liking = liking;
this.uses = uses;
}
}
理想情况下,这将转向......
{
"VARIABLE_WORD" : {
"joy" : 0.0,
"anger" : 0.8,
"sadness" : 0.0,
"fear" : 0.0,
"love" : 0.0,
"disliking" : 0.0,
"liking" : 0.0,
"uses" : 0
}
}
这最终将我带到了我正在编写/阅读价值观的地方,
public void write(String s) throws IOException {
ValuedWord temp = new ValuedWord(0,0.8,0,0,0,0,0,0);
generator.writeObject(temp);
}
public ValuedWord read(String s) throws IOException {
return mapper.readValue(new BufferedReader(new FileReader(path.toFile())), ValuedWord.class);
}
我希望我可以用 's' 做一些事情,但是,我找不到任何可以使用它的 'root' 的方法。
您可以使用ObjectWriter创建动态根元素名称。
public void write(String s) throws IOException {
ValuedWord temp = new ValuedWord(0,0.8,0,0,0,0,0,0);
ObjectWriter objectWriter = objectMapper.writer().withRootName(s);
String json = objectWriter.writeValueAsString(temp);
// Enhance your generator code to handle the json string
generator.writeObject(json);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.