这是我从Json文件中读取的第一个代码,但我不断收到错误消息: 无法从JasonElement转换为String
import java.io.FileReader;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Json
{
public static void main(String args[])
{
JsonParser parser = new JsonParser();
try
{
Object obj = parser.parse(new FileReader("C:\\Users\\dell\\eclipse-
workspace\\Assignment\\data.json"));
JsonObject jsonObject = (JsonObject) obj;
String name = (String) jsonObject.get("Name");
String author = (String) jsonObject.get("Author");
System.out.println("Name: " + name);
System.out.println("Author: " + author);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
对不起任何愚蠢的错误。 我还是初学者
答案 0 :(得分:1)
通过使用jsonObject.get(“Name”),您将获得一个JsonElement对象,并且无法转换为String。也许你可以试试:
wp_die();
答案 1 :(得分:0)
这取决于你想要什么。
如果((f, x)->f(x)).([f1, f2], x)
需要是实际的JSON字符串值(例如,它必须是Name
而不是 { "Name": "str" }
),那么您应该说{ {1}}。如果不是字符串,则会导致错误。
否则,使用{ "Name": [] }
作为jsonObject.get("Name").getAsString()
,它返回有效的JSON值。 E.g。
jsonObject.get("Name").toString()