bigbitecode
bigbitecode

Reputation: 263

Deserializing json and delimiting newlines NDJ

I have a simple JSON file I'd like to parse (units.json) using gson and Java:

{"user_name": "happyman", "status": {"hp": 20, "karma": 7, "mp": 10}, "gold": 5.25,}
{"user_name": "sadman", "status": {"hp": 10, "karma": 2, "mp": 6}, "gold": 0.5,}
...

The problem I have is, how do I parse this file as it is not in an array format?

Currently I have a Filereader to the path being called by the JsonReader

FileReader fileReader = new FileReader(jsonFilePath);
JsonReader jsonReader = new JsonReader(fileReader);
jsonReader.beginObject();
while (jsonReader.hasNext()) {
    String name = jsonReader.nextName();
    if (name.equals("user_name")) {
        System.out.println("user_id: "+jsonReader.nextString());
    }
    //...checks for other equals

However, with this code, I'm only able to get the first line. I have a feeling it has something to do with the "hasNext()" not being the right method call in the while loop.

I appreciate the help! Thanks.

Upvotes: 2

Views: 472

Answers (1)

randiel
randiel

Reputation: 290

You can use this code with GSON library:

ObjectMapper mapr = new ObjectMapper();
Map<String,Object> map = mapr.readValue(jsonString, Map.class);

or

public class Units {
  @JsonProperty("user_name")
  public String user_name;

  @JsonProperty("status")
  public List<Attr> attrs;

  ..
}
public class Attr {
  @JsonProperty("hp") 
  public String hp;
  @JsonProperty("karma") 
  public String karma;
  @JsonProperty("mp") 
  public String mp;
}

ObjectMapper mapr = new ObjectMapper();
Units unit = mapr.readValue(jsonString, Units.class);

for both you can use jsonString to define each json unit in your file.

Upvotes: 1

Related Questions