gpt4 book ai didi

java - 当没有标记所有内容时,如何使用 Gson 解析 Json 数据

转载 作者:行者123 更新时间:2023-11-30 06:02:45 35 4
gpt4 key购买 nike

我很高兴使用 Google Gson 来解析并提取表单的一些 JSON 元数据

{
"lowlevel": {
"average_loudness": 0.570070445538
},
"rhythm": {
"beats_count": 502,
"bpm": 128.347702026
},
"tonal": {
"chords_changes_rate": 0.0534749031067
"tuning_diatonic_strength": 0.431238204241,
"tuning_equal_tempered_deviation": 0.164615109563,
"tuning_frequency": 434.193115234,
"tuning_nontempered_energy_ratio": 0.847496032715
}
}

使用这个

public class AcousticBrainzLowlevelWrapper
{
private AcousticBrainzLowLevelRhythm rhythm;
private AcousticBrainzLowLevelTonal tonal;

public AcousticBrainzLowLevelRhythm getRhythm()
{
return rhythm;
}

public void setRhythm(AcousticBrainzLowLevelRhythm rhythm)
{
this.rhythm = rhythm;
}

public AcousticBrainzLowLevelTonal getTonal()
{
return tonal;
}

public void setTonal(AcousticBrainzLowLevelTonal tonal)
{
this.tonal = tonal;
}
}

 AcousticBrainzLowlevelWrapper low = gson.fromJson(result, AcousticBrainzLowlevelWrapper.class) ;

(完整的JSON可见here)

但现在 API 已扩展为允许多次查找,例如 url

现在返回

{
"96685213-a25c-4678-9a13-abd9ec81cf35": {
"0": {
"lowlevel": {
"average_loudness": 0.570070445538
},
"rhythm": {
"beats_count": 502,
"bpm": 128.347702026
},
"tonal": {
"chords_changes_rate": 0.0534749031067
"tuning_diatonic_strength": 0.431238204241,
"tuning_equal_tempered_deviation": 0.164615109563,
"tuning_frequency": 434.193115234,
"tuning_nontempered_energy_ratio": 0.847496032715
}
}
.....
"78787888-a25c-4678-9a13-abd9ec81cf35": {
"0": {
"lowlevel": {
......
..

区别在于 json 没有定义“96685213-a25c-4678-9a13-abd9ec81cf35”和“78787888-a25c-4678-9a13-abd9ec81cf35”是什么,或者“0”是什么。

所以我知道它们代表什么(MusicBrainzRecording 和 offset),但我无法创建像 AcousticBrainzLowlevelWrapper 这样的类来代表它,那么我如何解析这个新的 api。

更新我尝试创建

  public class AcousticBrainzLowLevelList
{
private Map<String, AcousticBrainzLowlevelWrapper> data = new HashMap<>();

public Map<String, AcousticBrainzLowlevelWrapper> getData()
{
return data;
}

public void setData(Map<String, AcousticBrainzLowlevelWrapper> data)
{
this.data = data;
}
}

然后调用

 AcousticBrainzLowLevelList lowMap = gson.fromJson(result, AcousticBrainzLowLevelList.class) ;

但 map 上没有添加任何内容。毫不奇怪,因为data我不知道如何给出名称,因为顶层没有一致的名称。

最佳答案

在我看来,您的输入 JSON 可以被解析以生成 Map<String,Map<Integer,AcousticBrainzLowlevelWrapper>> 类型的 Java 类。 :

Type type = new TypeToken<Map<String,Map<Integer,AcousticBrainzLowlevelWrapper>>>(){}.getType();
Map<String,Map<Integer,AcousticBrainzLowlevelWrapper>> result = gson.fromJson(json, type);

关于java - 当没有标记所有内容时,如何使用 Gson 解析 Json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51949078/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com