2010-09-30 6 views
-1

J'utilise Gson pour analyser les fichiers json d'un site Web. Je suis assez nouveau à Java et je veux savoir comment je devrais le faire.Création de classes à utiliser avec la bibliothèque Gson

Tout fonctionne bien mais j'ai quelques questions. Comme je reçois ces fichiers JSON d'un site Web sur lequel je n'ai aucun contrôle, certaines valeurs du fichier json sont nulles. Quelle est la bonne façon de travailler avec ceux-ci? J'ai des méthodes pour obtenir les valeurs de ma classe et changer pour le type désiré.

isp_ornd = "104% ou quelque chose de similaire à celle"

bsp_ornd = comme ci-dessus.

win_time = « 2m 35s 990 »

Comme je l'ai dit je ne suis pas avoir de problèmes que je veux juste savoir la manière correcte sur l'utilisation Gson et Java pour le faire.

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

}

Répondre

0

Il m'a fallu quelques essais, mais je pense que je comprends enfin ce que la question est. G12 n'a pas de mécanisme intégré pour transformer une chaîne JSON au format "23%" en Java int. Un désérialisateur personnalisé ou un traitement post-désérialisation serait nécessaire.

Il en va de même pour la conversion de l'heure personnalisée. Voici un exemple d'utilisation de Gson avec des désérialiseurs personnalisés pour traiter JSON comme ce que je comprends est ciblé.

input.json Contenu:

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

Exemple désérialiseurs pour gérer isp_ornd et 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; 
    } 
} 
Questions connexes