我正在尝试动态地将一些JSON解析为Map.以下适用于简单的JSON
String easyString = "{\"name\":\"mkyong\", \"age\":\"29\"}";
Map<String,String> map = new HashMap<String,String>();
ObjectMapper mapper = new ObjectMapper();
map = mapper.readValue(easyString,
new TypeReference<HashMap<String,String>>(){});
System.out.println(map);
Run Code Online (Sandbox Code Playgroud)
但是当我尝试将一些更复杂的JSON与嵌套信息一起使用时失败了.我正在尝试解析json.org中的示例数据
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": [
"GML",
"XML"
]
},
"GlossSee": "markup"
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
线程"main"中的异常com.fasterxml.jackson.databind.JsonMappingException:无法从START_OBJECT标记中反序列化java.lang.String的实例 …
我有一个JSON对象,我想从中获取密钥名称并将它们存储在ArrayList中.我使用了以下代码
jsonData(String filename) {
JsonParser parser = new JsonParser();
JsonElement jsonElement = null;
try {
jsonElement = parser.parse(new FileReader(filename));
} catch (JsonIOException | JsonSyntaxException | FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonObject jsonObject = jsonElement.getAsJsonObject();
int i = 0;
for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
String key = entry.getKey();
JsonElement value = entry.getValue();
keys.add(key);
i++;
}
nKeys = i;
}
Run Code Online (Sandbox Code Playgroud)
如果我将此代码与简单的JSON对象一起使用
{
"age":100,
"name":"mkyong.com",
"messages":["msg 1","msg 2","msg 3"]
}
Run Code Online (Sandbox Code Playgroud)
这很好用.年龄,名称和消息(不是值)被添加到我的ArrayList中.一旦我尝试使用这个相同的代码与更复杂的JSON这样
{"widget": {
"debug": "on",
"window": …Run Code Online (Sandbox Code Playgroud) 我有一个键盘插入linux盒子然后我在ssh上运行我的Java.我想知道是否有办法告诉Java监听来自特定键盘/终端的输入.由于我想要捕获的键盘插入物理机器而没有用户登录,我不确定有没有办法做到这一点,但我想我可能会问这里?
我正在尝试编写一个只能同时运行X(让我们说3个)线程的类.我有8个线程需要执行,但我只想让3一次运行,然后等待.一旦当前运行的线程之一停止,它将启动另一个.我不太清楚如何做到这一点.我的代码看起来像这样:
public class Main {
public void start() {
for(int i=0; i<=ALLTHREADS; i++) {
MyThreadClass thread = new MyThreadClass(someParam, someParam);
thread.run();
// Continue until we have 3 running threads, wait until a new spot opens up. This is what I'm having problems with
}
}
}
public class MyThreadClass implements Runnable {
public MyThreadClass(int param1, int param2) {
// Some logic unimportant to this post
}
public void run() {
// Generic code here, the point of this is to …Run Code Online (Sandbox Code Playgroud)