2016-10-28 13 views
2

我有這個整齊的數據格式,最好用對象作爲鍵來表示。所以我試着用下面的JSON:如何使用對象作爲JSON中的鍵?

{ 
    "blocks": { 
    "stone": { 
     { 
     "variant": ["bricks", "smooth"] 
     }: { 
     "sound": "guitar", 
     "particle": "guitar", 
     } 
    }, 
    "dirt": { 
     { 
     "variant": "dirt" 
     }: { 
     "sound": "square", 
     "particle": "note", 
     "volume": 0.5 
     } 
    } 
    } 
} 

但它給了我一個JsonSyntaxException。我使用GSON btw。我該如何做這項工作?

的數據結構:

import java.util.*; 
public class Instrument { 
    private final String name; 
    private final String particle; 
    private final float volume; 
    public Instrument(String name, Optional<String> particle, Optional<Float> volume) { 
    this.name = name; 
    this.particle = particle.orElse("note"); 
    this.volume = volume.orElse(1.0f); 
    } 
    /* getters and stuff */ 
} 

public class BlockType { 
    private final String name; 
    private final BlockStateMatcher state; 
    public BlockType(String name, BlockStateMatcher state) { 
    this.name = name; 
    this.state = state; 
    } 
    /* getters and stuff */ 
} 

import java.util.*; 
public class BlockStateMatcher { 
    private final Map<PropertyMap, Instrument> states; 
    /* etc */ 
} 

import java.util.*; 
public class PropertyMap extends HashMap<Property<T>, List<PropertyValue<T>>> /* simplified */ { 
    /* etc */ 
} 
+3

這不是有效的JSON語法。請參閱http://jsonlint.com/ –

+0

@ScaryWombat我不能以某種方式使用此語法嗎? – SoniEx2

+0

當然,但它不是JSON。 –

回答

5

你不能。這不是有效的JSON語法。

作爲每documentation,對象鍵必須是字符串,並根據spec

一個目的結構被表示爲一對大括號 的周邊零個或多個名稱/值對(或成員)。名稱是 字符串。

+0

那麼真的沒有辦法讓GSON接受這種JSON嗎? – SoniEx2

+0

@ SoniEx2,它不是一種JSON,所以不是。 – shmosel

+0

你可能會破解GSON來完成你的需求,但是你想解析的卻不是JSON。 –

1

您提供的文本是無效的json。

如果您的文本是

{ 
    "blocks": [{ 
     "name": "stone", 
     "variant": "bricks", 
     "sound": "guitar", 
     "particle": "guitar" 
    }, { 
     "name": "dirt", 
     "variant": "dirt", 
     "sound": "square", 
     "particle": "note", 
     "volume": 0.5 
    }] 
} 

您可能能夠解析它。

相關問題