使用数字作为标题转换Json对象

时间:2018-01-08 20:12:26

标签: java json gson

我正在使用的API将数字作为JSON标头返回。通常我只是从标题中创建一个类并使用Gson对其进行反序列化,但我不能这样做,因为标题是一个数字。这是一个Api样本

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

我尝试使用本主题中的最佳答案 How to convert json objects with number as field key in Java?但我收到了此错误

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

这是我的代码

   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);
            }
        }
    }

有没有办法修复此代码或替代它?

3 个答案:

答案 0 :(得分:1)

我在找到这篇文章后找到了我想要的答案: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
        }
    }
}

答案 1 :(得分:0)

这应该有效:

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 +
                '}';
    }
}

}

答案 2 :(得分:0)

我使用了一种变通方法,即在将字符串解析为json之前,对““ 263”:“进行字符串替换以将其替换为非数字值