我希望能够从 Java 操作方法中的 JSON 字符串访问属性。只需说出
myJsonString = object.getJson()
即可获得该字符串。下面是字符串的示例:
{
'title': 'ComputingandInformationsystems',
'id': 1,
'children': 'true',
'groups': [{
'title': 'LeveloneCIS',
'id': 2,
'children': 'true',
'groups': [{
'title': 'IntroToComputingandInternet',
'id': 3,
'children': 'false',
'groups': []
}]
}]
}
在此字符串中,每个 JSON 对象都包含其他 JSON 对象的数组。目的是提取 ID 列表,其中任何给定对象拥有包含其他 JSON 对象的组属性。我将 Google 的 Gson 视为潜在的 JSON 插件。谁能提供某种形式的指导来指导我如何从这个 JSON 字符串生成 Java?
我将 Google 的 Gson 视为潜在的 JSON 插件。谁能提供某种形式的指导来指导我如何从这个 JSON 字符串生成 Java?
Google Gson 支持泛型和嵌套 bean。 JSON 中的
[]
表示数组,应映射到 Java 集合,例如 List
或只是一个普通的 Java 数组。 JSON 中的 {}
表示一个对象,应该映射到 Java Map
或只是某个 JavaBean 类。
您有一个具有多个属性的 JSON 对象,其中
groups
属性表示完全相同类型的嵌套对象的数组。可以通过以下方式用 Gson 解析:
package com.stackoverflow.q1688099;
import java.util.List;
import com.google.gson.Gson;
public class Test {
public static void main(String... args) throws Exception {
String json =
"{"
+ "'title': 'Computing and Information systems',"
+ "'id' : 1,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Level one CIS',"
+ "'id' : 2,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Intro To Computing and Internet',"
+ "'id' : 3,"
+ "'children': 'false',"
+ "'groups':[]"
+ "}]"
+ "}]"
+ "}";
// Now do the magic.
Data data = new Gson().fromJson(json, Data.class);
// Show it.
System.out.println(data);
}
}
class Data {
private String title;
private Long id;
private Boolean children;
private List<Data> groups;
public String getTitle() { return title; }
public Long getId() { return id; }
public Boolean getChildren() { return children; }
public List<Data> getGroups() { return groups; }
public void setTitle(String title) { this.title = title; }
public void setId(Long id) { this.id = id; }
public void setChildren(Boolean children) { this.children = children; }
public void setGroups(List<Data> groups) { this.groups = groups; }
public String toString() {
return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
}
}
Gson#fromJson()
.
Gson 的 Bewaaaaare!这非常酷,非常棒,但是当您想做除简单对象之外的任何事情时,您可能很容易需要开始构建自己的序列化器(这并不难)。 此外,如果您有一个对象数组,并且将一些 json 反序列化到该对象数组中,则真正的类型将丢失!完整的对象甚至不会被复制!使用 XStream.. 如果使用 jsondriver 并设置正确的设置,会将丑陋的类型编码到实际的 json 中,这样你就不会丢失任何东西。真正的序列化要付出很小的代价(丑陋的 json)。
请注意,
Jackson修复了这些问题,并且比 GSON 更快。
这里还有更多不错的选择:
还有一个需要考虑的:
String json = "...";
ObjectMapper m = new ObjectMapper();
Set<Product> products = m.readValue(json, new TypeReference<Set<Product>>() {});
JSONObject
Java Object
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"id",
"firstName",
"lastName"
})
public class Employee {
@JsonProperty("id")
private Integer id;
@JsonProperty("firstName")
private String firstName;
@JsonProperty("lastName")
private String lastName;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* @return
* The id
*/
@JsonProperty("id")
public Integer getId() {
return id;
}
/**
*
* @param id
* The id
*/
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
/**
*
* @return
* The firstName
*/
@JsonProperty("firstName")
public String getFirstName() {
return firstName;
}
/**
*
* @param firstName
* The firstName
*/
@JsonProperty("firstName")
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
*
* @return
* The lastName
*/
@JsonProperty("lastName")
public String getLastName() {
return lastName;
}
/**
*
* @param lastName
* The lastName
*/
@JsonProperty("lastName")
public void setLastName(String lastName) {
this.lastName = lastName;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
import org.codehaus.jettison.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
public class LoadFromJSON {
public static void main(String args[]) throws Exception {
JSONObject json = new JSONObject();
json.put("id", 2);
json.put("firstName", "hello");
json.put("lastName", "world");
byte[] jsonData = json.toString().getBytes();
ObjectMapper mapper = new ObjectMapper();
Employee employee = mapper.readValue(jsonData, Employee.class);
System.out.print(employee.getLastName());
}
}
Message msgFromJSON = new ObjectMapper().readValue(jSONString, Message.class);
JSONObject jsonObject = new JSONObject(someJsonString);
JSONArray jsonArray = jsonObject.getJSONArray("someJsonArray");
String value = jsonArray.optJSONObject(i).getString("someJsonValue");
File file = new File("D:\\Coding\\tickets\\temp.json");
ObjectMapper om = new ObjectMapper();
Profile profile = om.readValue(file, new TypeReference<Profile>() {});
(在某些情况下高达 4 倍,并且经过了 100 次测试。它还有更快的索引覆盖模式。它还很年轻,但已经有一些用户了。)
它将 JSON 解析为地图和列表的速度比任何其他库解析为 JSON DOM 的速度都要快,并且没有索引覆盖模式。使用 Boon Index Overlay 模式,速度甚至更快。
它还有一个非常快的 JSON lax 模式和一个 PLIST 解析器模式。 :)(并且内存超低,直接从字节模式使用 UTF-8 即时编码)。
它还具有最快的 JSON 到 JavaBean 模式。
它是新的,但如果您正在寻找速度和简单的 API,我认为没有更快或更简约的 API。
Dto response = softConvertValue(jsonData, Dto.class);
public static <T> T softConvertValue(Object fromValue, Class<T> toValueType)
{
ObjectMapper objMapper = new ObjectMapper();
return objMapper
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.convertValue(fromValue, toValueType);
}
@Test
void readListJsonFromFileTest() throws IOException {
Type type = new TypeToken<List<SimplePojo>>(){}.getType();
String fromJsonFile = readFromJsonFile("json/simplePojoJsonList.json");
List<SimplePojo> pojoList = gson.fromJson(fromJsonFile, type);
Assertions.assertNotNull(pojoList);
}
@Test
void readJsonFromFileTest() throws IOException {
Type type = new TypeToken<SimplePojo>(){}.getType();
String fromJsonFile = readFromJsonFile("json/simplePojoJson.json");
SimplePojo simplePojo = gson.fromJson(fromJsonFile, type);
Assertions.assertNotNull(simplePojo);
}
String readFromJsonFile(String pathToJson) throws IOException {
InputStream resource = new ClassPathResource(pathToJson).getInputStream();
String json = StreamUtils.copyToString(resource, StandardCharsets.UTF_8);
return json;
}
标准,
<!-- https://mvnrepository.com/artifact/jakarta.json/jakarta.json-api -->
<dependency>
<groupId>jakarta.json</groupId>
<artifactId>jakarta.json-api</artifactId>
<version>2.1.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish/jakarta.json -->
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.json</artifactId>
<version>2.0.1</version>
</dependency>
JsonReader reader = Json.createReader(new StringReader(myJsonString));
JsonObject mainObject = reader.readObject();
JsonArray groups = mainObject.getJsonArray(groups);
JsonObject firstGroup = mainObject.getJsonObject(0);
int firstId = firstGroup.getInt("id")