0

The API I'm working with return a number as a JSON header. Normally I'd just make a class from the header and use Gson to deserialize it, but I cant do that since the header is a number. Here an Api Sample

   {"263": {"name": "George", "wage": 2000, "expenses": 1600}}

I tried to use the best Answer from this topic How to convert json objects with number as field key in Java? but I got this error

  com.google.gson.stream.MalformedJsonException: Use 
    JsonReader.setLenient(true) 
    to accept malformed JSON at line 1 column 7 path $

Here is my code

   public class checkapi {
        int wage263;
        int expenses263;
        //getters and setters
        public void set263() throws IOException, InterruptedException {
            JsonParser parser = new JsonParser();
            JsonObject obj = parser.parse("URL").getAsJsonObject();
            Set<Entry<String,JsonElement>> set = obj.entrySet();
            for (Entry<String,JsonElement> j : set) {
                int wage = obj.get("wage").getAsInt();
                int expenses = obj.get("expenses").getAsInt();
                setWage263(wage);
                setExpenses263(expenses);
            }
        }
    }

Is there any way to fix this code or an alternative for it?

H. Wortham
  • 11
  • 4

3 Answers3

1

I found the answer I was looking for after finding this post: Parse a nested JSON using gson.

public class checkapi {
        int wage263;
        int expenses263;
        //getters and setters
public void set263() throws IOException, InterruptedException {

        String json = readUrl(URL);

        JsonParser jsonParser = new JsonParser();
        JsonElement address = jsonParser.parse(json)
        .getAsJsonObject().get("263");
        int wage = ((JsonObject) address).get("wage").getAsInt();    

        JsonElement address2 = jsonParser.parse(json)
        .getAsJsonObject().get("263");
        int expenses = ((JsonObject) address2).get("expenses").getAsInt();

        setwage263(wage);
        setexpenses263(expenses);
    }


    private String readUrl(String string) throws IOException, InterruptedException {
        pause3(600);
        URL website = new URL(string);
        URLConnection connection = website.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        StringBuilder response = new StringBuilder();
        String inputLine;

        while ((inputLine = in.readLine()) != null)
            response.append(inputLine);

        in.close();

        return response.toString();
    }

    public static void pause3(long sleeptime) {
        long expectedtime = System.currentTimeMillis() + sleeptime;
        while (System.currentTimeMillis() < expectedtime) {
            // Empty Loop
        }
    }
}
H. Wortham
  • 11
  • 4
0

This should work:

public class Main {

public static void main(String[] args) {
    JsonParser parser = new JsonParser();
    JsonObject obj = parser.parse( " {\"263\": {\"name\": \"George\", \"wage\": 2000, \"expenses\": 1600}}").getAsJsonObject();
    List<Person> serializedList = new ArrayList<Person>();
    Set<Map.Entry<String,JsonElement>> set = obj.entrySet();
    for (Map.Entry<String,JsonElement> entry : set) {
        System.out.println("Key: " + entry.getKey());
        JsonObject jsonObject = entry.getValue().getAsJsonObject();

        Person person = new Person(
                jsonObject.get("name").getAsString(),
                jsonObject.get("wage").getAsInt(),
                jsonObject.get("expenses").getAsInt()
        );
        System.out.println(person);
        serializedList.add(person);
    }
    System.out.println(serializedList.size());

}

private static class Person {
    private String name;
    private Integer wage;
    private Integer expenses;

    public Person(String name, Integer wage, Integer expenses) {
        this.name = name;
        this.wage = wage;
        this.expenses = expenses;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", wage=" + wage +
                ", expenses=" + expenses +
                '}';
    }
}

}

0

I used a workaround by doing a string replace on ""263":" to replace it with a non numeric value prior to parsing the string into json