command reader: json reading

This commit is contained in:
Bixilon 2022-05-23 15:11:53 +02:00
parent 0971a7a1dc
commit 7d40f0ec2d
No known key found for this signature in database
GPG Key ID: 5CAD791931B09AC4
3 changed files with 53 additions and 0 deletions

View File

@ -14,6 +14,7 @@
package de.bixilon.minosoft.commands.util
import de.bixilon.kutil.cast.CastUtil.unsafeCast
import de.bixilon.kutil.json.JsonObject
import de.bixilon.minosoft.commands.errors.reader.*
import de.bixilon.minosoft.commands.errors.reader.map.DuplicatedKeyMapError
import de.bixilon.minosoft.commands.errors.reader.map.ExpectedKeyMapError
@ -22,6 +23,7 @@ import de.bixilon.minosoft.commands.errors.reader.map.InvalidMapSeparatorError
import de.bixilon.minosoft.commands.errors.reader.number.NegativeNumberError
import de.bixilon.minosoft.data.registries.ResourceLocation
import de.bixilon.minosoft.util.KUtil.toResourceLocation
import de.bixilon.minosoft.util.json.Jackson
open class CommandReader(val string: String) {
var pointer = 0
@ -359,6 +361,12 @@ open class CommandReader(val string: String) {
return map
}
fun readJson(): JsonObject {
skipWhitespaces()
return Jackson.MAPPER.readValue(JsonReader(this), Jackson.JSON_MAP_TYPE)
}
override fun toString(): String {
return string.substring(pointer, string.length)
}

View File

@ -0,0 +1,26 @@
/*
* Minosoft
* Copyright (C) 2020-2022 Moritz Zwerger
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This software is not affiliated with Mojang AB, the original developer of Minecraft.
*/
package de.bixilon.minosoft.commands.util
import java.io.Reader
class JsonReader(val reader: CommandReader) : Reader() {
override fun read(cbuf: CharArray, off: Int, len: Int): Int {
cbuf[0] = reader.readNext()?.toChar() ?: return 0
return 1
}
override fun close() = Unit
}

View File

@ -182,4 +182,23 @@ internal class CommandReaderTest {
assertEquals(read, "not")
assertFalse(negated)
}
@Test
fun readEmptyJson() {
val reader = CommandReader("{}")
assertEquals(reader.readJson(), emptyMap())
}
@Test
fun readBasicJson() {
val reader = CommandReader("""{"test": 123}""")
assertEquals(reader.readJson(), mapOf("test" to 123))
}
@Test
fun readJsonWithTrailingData() {
val reader = CommandReader("""{"test": 123} abc""")
assertEquals(reader.readJson(), mapOf("test" to 123))
assertEquals(reader.readString(), "abc")
}
}