Convert JSON Array to a Java Array or List with Jackson
介绍
在本文中,我们将使用Jackson将JSON数组转换为Java Array和Java List。
由于我们正在使用Jackson,因此您必须将其添加到您的项目中。如果您使用的是Maven,则就像添加依赖项一样简单:
1 2 3 4 5 | <dependency> <groupId>com.fasterxml.jackson.core</groupId> jackson-databind</artifactId> <version>2.11.2</version> </dependency> |
或者,如果您使用的是Gradle:
1 | compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.11.2' |
因为我们是从JSON映射到我们自己的对象,所以让我们继续定义POJO:
1 2 3 4 5 6 |
从字符串读取JSON
让我们从读取String开始。字符串包含一系列编程语言,并带有简短说明:
1 | String json ="[{"name":"Java","description":"Java is a class-based, object-oriented programming Language."},{"name":"Python","description":"Python is an interpreted, high-level and general-purpose programming Language."}, {"name":"JS","description":"JS is a programming Language that conforms to the ECMAScript specification."}]"; |
使用Jackson的
1 2 3 | // It's advised to use ObjectMapper as a singleton and reuse the instance final ObjectMapper ObjectMapper = new ObjectMapper(); Language[] langs = ObjectMapper.readValue(json, Language[].class); |
另外,您可以使用Jackson的
1 | List<Language> langList = ObjectMapper.readValue(json, new TypeReference<List<Language>>(){}); |
不建议使用
然后打印出值:
1 |
结果是:
1 2 3 | Language{name='Java', description='Java is a class-based, object-oriented programming Language.'} Language{name='Python', description='Python is an interpreted, high-level and general-purpose programming Language.'} Language{name='JS', description='JS is a programming Language that conforms to the ECMAScript specification.'} |
从文件读取JSON
我们并不总是处理String格式的JSON。通常,内容来自
1 2 3 4 5 6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | [ { "name":"Java", "description":"Java is a class-based, object-oriented programming Language that is designed to have as few implementation dependencies as possible." }, { "name":"Python", "description":"Python is an interpreted, high-level and general-purpose programming Language. Created by Guido van Rossum and first released in 1991." }, { "name":"JS", "description":"JS is a programming Language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm." } ] |
运行此代码将导致:
1 2 3 | Language{name='Java', description='Java is a class-based, object-oriented programming Language that is designed to have as few implementation dependencies as possible.'} Language{name='Python', description='Python is an interpreted, high-level and general-purpose programming Language. Created by Guido van Rossum and first released in 1991.'} Language{name='JS', description='JS is a programming Language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm.'} |
结论
在本文中,我们使用了Jackson来将JSON字符串和文件中的值解析并映射到Java数组和列表中。
通过