我正在使用以下程序:特别是Tomcat 8,VirtualBox虚拟机,& Gson 2.3.1
我试图在Gson中测试一个允许您将Java对象编组/解组为JSON格式的方法。
这是我使用它的代码(为了正确编译,两个类的java代码需要同时编译......:
最重要的是我的代码用于测试JSON转换方法:
package com.cs330;
import com.google.gson.Gson;
public class IngredientProto
{
public static void main (String[] args)
{
Ingredient neo = new Ingredient(6, "cheddar cheese", "cheese");
System.out.println("Object confirmed: " + neo.toString());
//New GSON object for marshalling...
Gson neoIngredient = new Gson();
//Use said object to create the JSON formatted String for this Ingredient (Object).
String jsonThis = neoIngredient.toJson(neo);
//Printing out the new object (Ingredient)...
System.out.println ("Object formatted to JSON: " + jsonThis);
//Convert Back via unmarshalling. NOW!
Ingredient orga = neoIngredient.fromJson(jsonThis, Ingredient.class);
//Print Again!
System.out.println("Reverting back into Object variable: " + orga.toString());
}
}
这里,作为参考,是我的成分类I的代码&m;使用...
package com.cs330;
import java.util.Scanner;
public class Ingredient //implements Comparable<Ingredient>
{
private int ingredientID;
private String ingredientName;
protected String ingredientType;
//DEFAULT CONSTRUCTOR
Ingredient()
{
this.ingredientID = 0;
this.ingredientName = "No Ingredient";
this.ingredientType = "No Type";
}
//CONSTRUCTOR 1 - Parameters for Name, ID, and Type.
Ingredient(int ingredientID, String ingredientName, String ingredientType)
{
setIngredientID(ingredientID);
setIngredientName(ingredientName);
setIngredientType(ingredientType);
}
//CONSTRUCTOR 2 - Parameters for Name and Type.
Ingredient(String ingredientName, String ingredientType)
{
this.ingredientID = 0;
setIngredientName(ingredientName);
setIngredientType(ingredientType);
}
//Getters and Setters Go here.
//TO STRING
public String toString()
{
String results = " ";
results = this.ingredientID + ": " + this.ingredientName
+ " (" + this.ingredientType + ") ";
return results;
}//END toSTRING
//...Main for testing...
}//END PROGRAM
每当我尝试在我的虚拟机上使用CMD编译它们时,我一直遇到的错误包括:
error: package com.google.gson does not exist
- 我已经导入了com.google.gson.Gson,它需要在我的程序中,但我一直收到此错误,我的代码没有任何问题... error: class, interface, or enum expected
- 我实际上添加了com.google.gson包,但是我发现了这个错误,尽管其他一切都是正确的。当我尝试测试Gson程序代码时,以及我创建的Ingredient类,都会发生这两个错误。我真正关心的是如何才能有效地解决这个问题......
答案 0 :(得分:1)
在命令提示符下编译时,使用-cp或-classpath在类路径中设置gson.jar。像这样:
javac -classpath <LOCATION_TO_GSON JAR FILE> *.java
在运行时检查gson库是否存在于类路径中(WEB-INF/lib
或\apache-tomcat-7.0.42\lib
)
答案 1 :(得分:0)
在运行时和Tomcat classpath中需要Gason jar文件在classpath of your development environment进行编译。