2015-04-28 61 views
0

我开发了一个Android应用程序,我必须反序列化一个JSON文件。 我有这些类:使用GSON反序列化JSON文件

public class Medicine { 

    @SerializedName("substanta_activa") 
    private List<String> active_substance; 
    @SerializedName("produse") 
    private List<Product> product; 
    @SerializedName("dozaj") 
    private Dosage dosage; 
    @SerializedName("mentiuni") 
    private List<String> notes; 
    @SerializedName("cuvinte_cheie") 
    private List<String> keyword; 

    /* + getters and setters */ 
} 

public class Product { 

    @SerializedName("denumire_comerciala") 
    private String productName; 

    @SerializedName("forme_de_prezentare") 
    private List<String> form; 

    /* + getters and setters */ 
} 

public class Dosage { 
    @SerializedName("nounascuti") 
    private String newborn; 

    @SerializedName("copii") 
    private String child; 

    @SerializedName("adulti") 
    private String adult; 

    /* + getters and setters */ 
} 

而且我有以下的JSON文件:

[ 
    { 
     "substanta_activa": [ 
      "trimebutinum" 
     ], 
     "produse": [ 
      { 
       "denumire_comerciala": "Debridat", 
       "forme_de_prezentare": [ 
        "susp. buvabilă", 
        "susp. 24mg/5ml în flac 250ml", 
        "compr 100mg" 
       ] 
      }, 
      { 
       "denumire_comerciala": "Ibutin", 
       "forme_de_prezentare": [ 
        "compr 300mg" 
       ] 
      }, 
      { 
       "denumire_comerciala": "Trimebutin", 
       "forme_de_prezentare": [ 
        "compr 100mg" 
       ] 
      }, 
      { 
       "denumire_comerciala": "Colperin", 
       "forme_de_prezentare": [ 
        "compr 100mg" 
       ] 
      } 
     ], 
     "dozaj": { 
      "nounascuti": "1ml/kg/zi div 3,", 
      "copii": "1ml/kg/zi div 3, peste 5 ani 3x10ml", 
      "adulti": "3x1-2 compr/zi, 1x300mg/zi sau 3x1-2 lingură/zi" 
     }, 
     "mentiuni": [ 
      "se poate administra de la naștere", 
      "se poate administra amestecat cu apă, lapte", 
      "10ml conține 6g zahăr" 
     ], 
     "cuvinte_cheie": [ 
      "gastro", 
      "colică", 
      "dureri abdominale funcționale", 
      "constipație" 
     ] 
    }, 
    { 
     "substanta_activa": [ 
      "benzydaminum" 
     ], 
     "produse": [ 
      { 
       "denumire_comerciala": "Tantum Verde comprimate", 
       "forme_de_prezentare": [ 
        "pastile pt supt 3mg" 
       ] 
      }, 
      { 
       "denumire_comerciala": "Tantum Verde spray", 
       "forme_de_prezentare": [ 
        "spray bucofaringian 0,15%, 0,3%" 
       ] 
      } 
     ], 
     "dozaj": { 
      "nounascuti": "contraindicat", 
      "copii": "2-6 ani: 2-6x1 puf/4kg; >6 sni: 2-6x 4doze sau 3x1 pastila/zi", 
      "adulti": "2-6x 4puf sau 3x1 pastila/zi" 
     }, 
     "mentiuni": [ 
      "se admin. max. 7 zile" 
     ], 
     "cuvinte_cheie": [ 
      "antiseptic, anestezic, antiinflamator, oral, OTC" 
     ] 
    } 
] 

我尝试了好几种方式,有GSON和无它也是如此,但没有成功。提前谢谢你的帮助。

编辑更

一点点细节: 我有一个MainPageActivity,在那里我初始化一个InputStream,设置路径,并呼吁从JSONParser类我反序列化方法:

InputStream is = null; 
String internalStoragePath = getApplicationContext().getFilesDir().getAbsolutePath(); 
File fileToInternalStorage = new File(internalStoragePath + "/medicinelist.json"); 
try { 
    is = new FileInputStream(fileToInternalStorage); 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
if (is == null) { 
    is = getResources().openRawResource(R.raw.gyogyszerek); 
} 
jsonParser = new JSONParser(); 
try { 
    medicines = jsonParser.readJsonStream(getApplicationContext(), is); 
    //medicines = jsonParser.jsonDeserializer(getApplicationContext(), is); 
    is.close(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

在我JSONParser类,正如我所提到的,我尝试了几种方法来反序列化JSON输入。 这里是“传统”的方式,与Android内置的JsonReader类(对不起,有点长):

public ArrayList readJsonStream(Context applicationContext, InputStream in) throws IOException { 
    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); 

    try { 
     return readMedicineArray(reader); 
    } finally { 
     reader.close(); 
    } 
} 


public ArrayList readMedicineArray(JsonReader reader) throws IOException { 
    ArrayList medicines = new ArrayList(); 
    reader.beginArray(); 
    while (reader.hasNext()) { 
     medicines.add(readMedicine(reader)); 
    } 
    reader.endArray(); 
    return medicines; 
} 

public Medicine readMedicine(JsonReader reader) throws IOException { 
    List active_substance = null; 
    List product = null; 
    Dosage dosage = null; 
    List notes = null; 
    List keyword = null; 

    reader.beginObject(); 
    while (reader.hasNext()) { 
     String name = reader.nextName(); 

     if (name.equals("substanta_activa")) { 
      active_substance = readActiveSubstanceArray(reader); 
     } else if (name.equals("produse")) { 
      product = readProductArray(reader); 
     } else if (name.equals("dozaj")) { 
      dosage = readDosage (reader); 
     } else if (name.equals("mentiuni") && reader.peek() != JsonToken.NULL) { 
      notes= readNotesArray(reader); 
     } else if (name.equals("cuvinte_cheie") && reader.peek() != JsonToken.NULL) { 
      keyword = readKeywordArray(reader); 
     } else { 
      reader.skipValue(); 
     } 
    } 
    reader.endObject(); 
    return new Medicine(active_substance, product, dosage, notes, keyword); 
} 

public List readActiveSubstanceArray(JsonReader reader) throws IOException { 
    List active_substance = new ArrayList(); 

    reader.beginArray(); 
    while (reader.hasNext()) { 
     active_substance.add(reader.nextString()); 
    } 
    reader.endArray(); 
    return active_substance; 
} 

public List readProductArray(JsonReader reader) throws IOException { 
    List product = new ArrayList(); 

    reader.beginArray(); 
    while (reader.hasNext()) { 
     product.add(readProduct(reader)); 
    } 
    reader.endArray(); 
    return product; 
} 

public Product readProduct(JsonReader reader) throws IOException { 
    String productName = null; 
    List form = null; 

    reader.beginObject(); 
    while (reader.hasNext()) { 
     String name = reader.nextName(); 
     if (name.equals("denumire_comerciala")) { 
      productName = reader.nextString(); 
     } else if (name.equals("forme_de_prezentare")) { 
      form = readFormArray(reader); 
     } else { 
      reader.skipValue(); 
     } 
    } 
    reader.endObject(); 
    return new Product(productName, form); 
} 

public List readFormArray(JsonReader reader) throws IOException { 
    List form = new ArrayList(); 

    reader.beginArray(); 
    while (reader.hasNext()) { 
     form.add(reader.nextString()); 
    } 
    reader.endArray(); 
    return form; 
} 

public Dosage readDosage(JsonReader reader) throws IOException { 
    String newborn= null; 
    String child= null; 
    String adult= null; 

    reader.beginObject(); 
    while (reader.hasNext()) { 
     String name = reader.nextName(); 
     if (name.equals("nounascuti")) { 
      newborn= reader.nextString(); 
     } else if (name.equals("copii")) { 
      child= reader.nextString(); 
     } else if (name.equals("adulti")) { 
      adult= reader.nextString(); 
     } else { 
      reader.skipValue(); 
     } 
    } 
    reader.endObject(); 
    return new Dosage(newborn, child, adult); 
} 

public List readNotesArray(JsonReader reader) throws IOException { 
    List notes= new ArrayList(); 

    reader.beginArray(); 
    while (reader.hasNext()) { 
     notes.add(reader.nextString()); 
    } 
    reader.endArray(); 
    return notes; 
} 

public List readKeywordArray(JsonReader reader) throws IOException { 
    List keyword= new ArrayList(); 

    reader.beginArray(); 
    while (reader.hasNext()) { 
     keyword.add(reader.nextString()); 
    } 
    reader.endArray(); 
    return keyword; 
} 

这里是另一种方式与GSON库:

public ArrayList<Medicine> jsonDeserializer(Context contexts, InputStream in) throws IOException { 
     Reader reader = new InputStreamReader(in); 

     ArrayList medicinesList = new ArrayList(); 
     final GsonBuilder gsonBuilder = new GsonBuilder(); 
     final Gson gson = gsonBuilder.create(); 

     Medicine[] medicinesArray = new Gson().fromJson(reader, Medicine[].class); 
     for(int i = 0; i < medicinesArray.length; ++i){ 
      medicinesList.add(medicinesArray[i]); 
     } 

     return medicinesList; 
} 

无其中的作品,但我不知道是什么问题。

+0

*“没有成功”是什么意思*?发生什么事?你的反序列化代码在哪里? – mkobit

回答

1

//试试这个

Gson gson = new Gson(); 
    Type listType = new TypeToken<ArrayList<Medicine>>() {}.getType(); 
    List<Medicine> medList = gson.fromJson(<YOUR JSON STRING>, listType); 
+0

jsonObject从哪里来?它是一个GSON类型变量吗? –

+0

修改答案请试试这个。 – Manish

+0

不幸的是,它现在不起作用。 –

0

使用这种方法:

public static <T> T JsonParse(T t, String response) 
      throws JsonSyntaxException, IOException, XmlPullParserException { 
     InputStream in = new ByteArrayInputStream(response.getBytes()); 
     JsonReader reader; 
     reader = new JsonReader(new InputStreamReader(in, "UTF-8")); 
     GsonBuilder b = new GsonBuilder(); 
     Gson gson = b.create(); 
     t = (T) gson.fromJson(reader, t.getClass()); 
     reader.close(); 
     return t; 
    } 

使用这种方法:

ArrayList<Medicine> arrlist=JsonParse(new Medicine(),JsonResponse); 

我希望它的对你有用。

+0

BooleanSerializer类是做什么的? –

+0

sorry..sorry.please删除此内容...检查编辑答案 – dipali

+0

booleanserializer用于在json字符串中获取布尔0或1而不是true或false时使用。 – dipali

0

1)首先创建类是这样的:

public class Produse 
{ 
public String Denumire_comerciala; 
public List<String > Forme_de_prezentare; 
} 

public class Dosage 
{ 
public String Nounascuti; 
public String Copii; 
public String Adulti; 
} 

public class RootObject 
{ 
public List<String > Substanta_activa; 
public List<Produse> Produse; 
public Dosage Dozaj; 
public List<String > Mentiuni; 
public List<String > Cuvinte_cheie; 
} 

2)然后,以这种方式使用GSON像:

Gson _gson = new GsonBuilder().create(); 
RootObject root= gson.fromJson("*YOUR JSON HERE*", RootObject .class); 

希望这将有助于。

+0

我的JSON文件包含更多的对象,而不仅仅是一个,因此单个RootObject实例是不够的,是吗? –

+0

您是否设定了我的密码? RootObject包含列表对象。 –

+0

是的,我做了,我得到了一个错误,因为它只返回一个RootObject类型的对象,但是我的文件包含更多它,并且它们都包含Substanta_activa列表,Produse列表等等,所以我需要一个RootObject列表类型的对象。 –