変換JSONデータをJavaオブジェクト
質問
こういうことができるようにアクセス性またはJSON文字列内にJavaの行動方法です。文字列に使用可能になっ 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の引き出しおよび設定ができます誰でもできるのでいくつかのフォームを提供しのご案内しているかを生成できるJavaからこのJSON文字列?
解決
私は、潜在的な JSON プラグインとして Google の Gson を検討しました。この JSON 文字列から Java を生成する方法について何らかのガイダンスを提供できる人はいますか?
Google Gson ジェネリックとネストされた Bean をサポートします。の []
JSON の は配列を表し、次のような Java コレクションにマップする必要があります。 List
または単なる Java 配列。の {}
JSON の はオブジェクトを表し、Java にマップする必要があります Map
または単なる JavaBean クラス。
いくつかのプロパティを持つ JSON オブジェクトがあります。 groups
property は、まったく同じタイプのネストされたオブジェクトの配列を表します。これは、次の方法で 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);
}
}
とてもシンプルですね。適切な JavaBean を用意して呼び出すだけです Gson#fromJson()
.
以下も参照してください。
- Json.org - JSON の概要
- Gson ユーザーガイド - Gson の紹介
他のヒント
またはジャクソンとます:
String json = "...
ObjectMapper m = new ObjectMapper();
Set<Product> products = m.readValue(json, new TypeReference<Set<Product>>() {});
、任意の変更によって、あなたはすでにそれから http://restfb.com/ に使用するアプリケーションである場合あなたが行うことができます:
import com.restfb.json.JsonObject;
...
JsonObject json = new JsonObject(jsonString);
json.get("title");
など。
変換するのが簡単で機能する Java コード JSONObject
に Java Object
従業員.java
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);
}
}
LoadFromJSON.java
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());
}
}
HashMap keyArrayList = new HashMap();
Iterator itr = yourJson.keys();
while (itr.hasNext())
{
String key = (String) itr.next();
keyArrayList.put(key, yourJson.get(key).toString());
}
標準のものと何が問題なのですか?
JSONObject jsonObject = new JSONObject(someJsonString);
JSONArray jsonArray = jsonObject.getJSONArray("someJsonArray");
String value = jsonArray.optJSONObject(i).getString("someJsonValue");
恩恵を試してみてください。
https://github.com/RichardHightower/boonする
これは、邪悪な高速です。
https://github.com/RichardHightower/json-parsers-benchmarkする
それは私の言葉を服用しないでください...ガトリングベンチマークをチェックアウトします。
https://github.com/gatling/json-parsers-benchmarkする
(4倍までは、テストの100Sのうちのいくつかの例である。また、さらに高速であるインデックス・オーバーレイモードを持っている。それは若いですが、すでに一部のユーザーを持っています。)
これは、JSON DOMに解析することができます速く、他のlibに比べてマップとリストにJSONを解析することができ、それがインデックスオーバーレイモードなしです。ブーンインデックスオーバーレイモードでは、それも高速です。
また、非常に高速なJSONずさんモードとPLISTパーサモードを備えています。 :)(超低メモリを有し、オンザフライでUTF-8エンコーディングでバイトモードから直接)。
これは、あまりにもJavaBeanのモードへの最速JSONを持っています。
これは新しいですが、スピードとシンプルなAPIは、あなたが探しているものであれば、私はより速く以上のミニマリストのAPIがあるとは思いません。
入力JSON形式(文字列/ファイル)に応じjSONStringを作成します。 JSONに対応するサンプルメッセージクラスオブジェクトは以下のように得ることができる:
メッセージmsgFromJSON =新しいObjectMapper()readValue(jSONString、Message.class)。
最も簡単な方法は、あなたがあなたの特定のDTOクラスにjsonDataを変換することが可能なカスタムメソッドであるこのsoftconvertvalueメソッドを使用することができるということです。
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);
}