-10

I tried to retrieve the parameter 'position' and its X and Y.

int npcId = reader.get("npcId").getAsInt();
int x = reader.get("position").getAsInt();
int y = reader.get("position").getAsInt();
int z = 0;

from this input, which is JSON

{
    "npcId": 414,
    "position": {
        "x": 3443,
        "y": 3536,
        "z": 0
    },
    "facing": "WEST",
    "radius": 13
}

For example int x = reader.get("position.X").getAsInt(); (Which obviously doesn't work but you get the idea.)

juzraai
  • 4,835
  • 8
  • 26
  • 41
Mike
  • 3

1 Answers1

0

As I see from your post, you want to parse JSON input and retrieve values of some fields.

Here is an example, if you want to create a Java class corresponding to your JSON structure. Then you build an object from your JSON and retrieve the field directly. https://www.journaldev.com/2321/gson-example-tutorial-parse-json

Another way, which I did, is to build a map from your JSON, and iterate through it. In this case, you should know your JSON structure. This is an example, https://stackoverflow.com/a/12296567/4587961

1) Parse input String into a JSON object.

2) Iterate through the JSON object and find the fields you need.

3) Retrieve their values.

compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'

Gson gson = new Gson(); 
String json = "{\"k1\":\"v1\",\"k2\":\"v2\"}";//You input String
Map<String,Object> map = new HashMap<String,Object>();
//Check if map is not null and instance of Map.
map = (Map<String,Object>) gson.fromJson(json, map.getClass());
Object position = map.get("position");
//Check if position is not null and instance of Map. You can create a method to do this logic.
Map<String, Object> positionMap = (Map) position;
Object X = positionMap.get("x");
//Please, continue yourself.

Also you could use other libraries, for example, Jackson. This is your homework, try to learn more about JSON, and try different libraries, and a link to your github account with examples, so other people can also learn.

Yan Khonski
  • 9,178
  • 13
  • 52
  • 88
  • Thanks for your reply, this is my first post here and I don't quite understand how this website works =\ I still don't quite understand what you mean, It is JSON, If I post more code could you correct it for me ? Thank you. – Mike Jul 24 '18 at 11:20
  • public static JsonLoader parse() { return new JsonLoader() { @Override public void load(JsonObject reader, Gson builder) { int npcId = reader.get("npcId").getAsInt(); int x = reader.get("position").getAsInt(); int y = reader.get("position").getAsInt(); int z = 0; if(reader.has("z")) { z = reader.get("z").getAsInt(); } //Spawn npc World.getNpcAddQueue().add(new NPC(npcId, new Position(x, y, z))); } – Mike Jul 24 '18 at 11:21
  • 1
    @Mike if you feel like showing more code is helpful, kindly do so in your question. Not in comments. – kumesana Jul 24 '18 at 11:29