创建与 Gson 库一起使用的类

发布于 2024-09-25 23:19:52 字数 2010 浏览 2 评论 0原文

我正在使用 Gson 解析网站上的 json 文件。我对 Java 很陌生,想找出我应该这样做的正确方法。

一切正常,但我有几个问题。由于我从我无法控制的网站获取这些 Json 文件,因此 json 文件中的某些值为空。处理这些的正确方法是什么?我有 get 方法从我的类中获取值并更改为所需的类型。

isp_ornd =“104%或类似的东西”

bsp_ornd =如上所述。

win_time = "2m 35s 990"

正如我所说,我没有任何问题,我只是想找出使用​​ Gson 和 Java 执行此操作的正确方法。

public class ResultData {
    private String isp_ornd;
    private String bsp_ornd;
    private String win_time;
    private RunnerData[] runners;

public int getIspOrnd() {
    if(isp_ornd != null){
        isp_ornd = isp_ornd.replace("%", "");
        isp_ornd = isp_ornd.replace(" ", "");
        if(isp_ornd.equals(""))
            isp_ornd = "0";
        return Integer.parseInt(isp_ornd);
    }
    else
        return 0;
}

public int getBspOrnd() {
    if(bsp_ornd != null){
        bsp_ornd = bsp_ornd.replace("%", "");
        bsp_ornd = bsp_ornd.replace(" ", "");
        if(bsp_ornd.equals(""))
            bsp_ornd = "0";
        return Integer.parseInt(bsp_ornd);
    }
    else
        return 0;
}

public long getWinTime() {
    long minutes = 0;
    long seconds = 0;
    long milliseconds = 0;
    long totalTime = 0;
    if(win_time != null){
        win_time = win_time.replace("m ",":");
        win_time = win_time.replace(".",":");
        win_time = win_time.replace("s","");
        win_time = win_time.replace(" ","");

        String[] timeSplit = win_time.split(":");

        if(timeSplit.length  == 3){
            minutes = Long.parseLong(timeSplit[0]);
            seconds = Long.parseLong(timeSplit[1]);
            milliseconds = Long.parseLong(timeSplit[2]);
            totalTime = (minutes * 36000) + (seconds * 1000) + (milliseconds*10);
        }
        else
            totalTime = 0;
    }
    else
        totalTime = 0;

    return totalTime;
}

public RunnerData[] getRunners() {
    return runners;
}

public String toString(){
    return getIspOrnd() + " " +  getBspOrnd() + " " + getWinTime() + " " + win_time;
}

}

I am using Gson to parse json files from a website. I am quite new at Java and want to find out the correct way i should be doing this.

Everything is working fine but i have a few questions. Since i am getting these Json files from a website i have no control over, some of the values in the json file are null. What is the proper way to work with these? I have get methods to get the values from my class and change to the desired type.

isp_ornd = "104% or something similar to that"

bsp_ornd = as above.

win_time = "2m 35s 990"

As i said im not having any problems i just want to find out the correct way on using Gson and Java for doing this.

public class ResultData {
    private String isp_ornd;
    private String bsp_ornd;
    private String win_time;
    private RunnerData[] runners;

public int getIspOrnd() {
    if(isp_ornd != null){
        isp_ornd = isp_ornd.replace("%", "");
        isp_ornd = isp_ornd.replace(" ", "");
        if(isp_ornd.equals(""))
            isp_ornd = "0";
        return Integer.parseInt(isp_ornd);
    }
    else
        return 0;
}

public int getBspOrnd() {
    if(bsp_ornd != null){
        bsp_ornd = bsp_ornd.replace("%", "");
        bsp_ornd = bsp_ornd.replace(" ", "");
        if(bsp_ornd.equals(""))
            bsp_ornd = "0";
        return Integer.parseInt(bsp_ornd);
    }
    else
        return 0;
}

public long getWinTime() {
    long minutes = 0;
    long seconds = 0;
    long milliseconds = 0;
    long totalTime = 0;
    if(win_time != null){
        win_time = win_time.replace("m ",":");
        win_time = win_time.replace(".",":");
        win_time = win_time.replace("s","");
        win_time = win_time.replace(" ","");

        String[] timeSplit = win_time.split(":");

        if(timeSplit.length  == 3){
            minutes = Long.parseLong(timeSplit[0]);
            seconds = Long.parseLong(timeSplit[1]);
            milliseconds = Long.parseLong(timeSplit[2]);
            totalTime = (minutes * 36000) + (seconds * 1000) + (milliseconds*10);
        }
        else
            totalTime = 0;
    }
    else
        totalTime = 0;

    return totalTime;
}

public RunnerData[] getRunners() {
    return runners;
}

public String toString(){
    return getIspOrnd() + " " +  getBspOrnd() + " " + getWinTime() + " " + win_time;
}

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱人如己 2024-10-02 23:19:52

我尝试了几次,但我想我终于明白了问题所在。

Gson 没有内置机制将 "23%" 格式的 JSON 字符串转换为 Java int。自定义解串器或解串后处理都是必要的。

自定义时间转换也是如此。

以下是使用 Gson 与自定义反序列化器来处理 JSON 的示例,就像我所理解的目标一样。

input.json 内容:

{
  "isp_ornd":"104%",
  "bsp_ornd":"64%",
  "win_time":"2m 35s 990"
}

处理 isp_orndwin_time 格式的示例反序列化器:

import java.io.FileReader;
import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;

public class Foo
{
  int isp_ornd;
  int bsp_ornd;
  long win_time;
  int num1;
  long num2;

  public static void main(String[] args) throws Exception
  {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(int.class, new PercentIntDeserializer());
    gsonBuilder.registerTypeAdapter(long.class, new TimeLongDeserializer());
    Gson gson = gsonBuilder.create();
    Foo foo = gson.fromJson(new FileReader("input.json"), Foo.class);
    System.out.println(gson.toJson(foo));
  }
}

class PercentIntDeserializer implements JsonDeserializer<Integer>
{
  @Override
  public Integer deserialize(JsonElement json, Type integerType, JsonDeserializationContext context)
      throws JsonParseException
  {
    if (json.isJsonNull()) return 0;
    String input = json.getAsString();
    JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive();
    if (jsonPrimitive.isNumber()) return json.getAsInt();

    input = input.replace("%", "");
    input = input.replaceAll(" ", "");
    if (input.length() == 0) return 0;
    return Integer.parseInt(input);
  }
}

class TimeLongDeserializer implements JsonDeserializer<Long>
{
  @Override
  public Long deserialize(JsonElement json, Type longType, JsonDeserializationContext context) 
      throws JsonParseException
  {
    if (json.isJsonNull()) return 0L;
    JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive();
    if (jsonPrimitive.isNumber()) return json.getAsLong();

    String input = json.getAsString();
    input = input.replace("m", ":");
    input = input.replace(".", ":");
    input = input.replace("s", ":");
    input = input.replaceAll(" ", "");
    if (input.length() == 0) return 0L;
    String[] timeSplit = input.split(":");
    if (timeSplit.length != 3) return 0L;
    long minutes = Long.parseLong(timeSplit[0]);
    long seconds = Long.parseLong(timeSplit[1]);
    long millis = Long.parseLong(timeSplit[2]);
    return minutes * 36000 + seconds * 1000 + millis * 10;
  }
}

It took me a few tries, but I think I finally understand what the question is.

Gson does not have a built-in mechanism to transform a JSON string in the format "23%" into a Java int. Either a custom deserializer or post-deserialization processing would be necessary.

Same goes for the custom time conversion.

Following is an example of using Gson with custom deserializers to process JSON like what I understand is targeted.

input.json Contents:

{
  "isp_ornd":"104%",
  "bsp_ornd":"64%",
  "win_time":"2m 35s 990"
}

Example Deserializers to handle isp_ornd and win_time formats:

import java.io.FileReader;
import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;

public class Foo
{
  int isp_ornd;
  int bsp_ornd;
  long win_time;
  int num1;
  long num2;

  public static void main(String[] args) throws Exception
  {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(int.class, new PercentIntDeserializer());
    gsonBuilder.registerTypeAdapter(long.class, new TimeLongDeserializer());
    Gson gson = gsonBuilder.create();
    Foo foo = gson.fromJson(new FileReader("input.json"), Foo.class);
    System.out.println(gson.toJson(foo));
  }
}

class PercentIntDeserializer implements JsonDeserializer<Integer>
{
  @Override
  public Integer deserialize(JsonElement json, Type integerType, JsonDeserializationContext context)
      throws JsonParseException
  {
    if (json.isJsonNull()) return 0;
    String input = json.getAsString();
    JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive();
    if (jsonPrimitive.isNumber()) return json.getAsInt();

    input = input.replace("%", "");
    input = input.replaceAll(" ", "");
    if (input.length() == 0) return 0;
    return Integer.parseInt(input);
  }
}

class TimeLongDeserializer implements JsonDeserializer<Long>
{
  @Override
  public Long deserialize(JsonElement json, Type longType, JsonDeserializationContext context) 
      throws JsonParseException
  {
    if (json.isJsonNull()) return 0L;
    JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive();
    if (jsonPrimitive.isNumber()) return json.getAsLong();

    String input = json.getAsString();
    input = input.replace("m", ":");
    input = input.replace(".", ":");
    input = input.replace("s", ":");
    input = input.replaceAll(" ", "");
    if (input.length() == 0) return 0L;
    String[] timeSplit = input.split(":");
    if (timeSplit.length != 3) return 0L;
    long minutes = Long.parseLong(timeSplit[0]);
    long seconds = Long.parseLong(timeSplit[1]);
    long millis = Long.parseLong(timeSplit[2]);
    return minutes * 36000 + seconds * 1000 + millis * 10;
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文