JavaクラスライブラリであるGSONは、JavaオブジェクトをJSONに変換するか、JSON文字列を等しいJavaオブジェクトに変換できます。 GSONは、ソースコードのないオブジェクトを含む任意の複雑なJavaオブジェクトをサポートしています。
他のJSON解析ライブラリには、JSON-LIBが含まれます。ジャクソン; com.alibaba.fastjson
私はまだGoogleのGSONが好きです。
1。シナリオを使用します:
JavaオブジェクトとJSON文字列の変換。ログ出力。
例えば:
logger logger = logger.getLogger(commonaction.class); gson g = new gson(); logger.info( "return:"+g.tojson(map));
2。使用の例:
1.基本的な使用トジソン
tojason()メソッドは、オブジェクトをJSON文字列に変換します
gson gson = new gson(); list persons = new arrayList(); string str = gson.tojson(persons);
2。基本的な使用法:fromjson()
GSONは、JSON文字列からJavaエンティティに変換する方法を実装するために、fromjson()方法を提供します。
たとえば、JSON文字列は次のとおりです。
[{"name": "name0"、 "age":0}]しかし:
人の人= gson.fromjson(str、person.class);
2つのパラメーター、つまりJSON文字列と変換する必要があるオブジェクトのタイプを提供します。
3.ユニコードエスケープを避けてください
たとえば、{"s": "/u003c"}このように印刷するだけで{"s": "<"}ソリューション:HTMLエスケープを無効にする必要があります。 gson gson = new
gsonbuilder()。disablehtmlescaping()。create();
4.特定のフィールドを除外します
クラスAにField Field1が含まれ、その親クラスにもField Field1が含まれている場合、JSONへのオブジェクトがField1という名前の複数のJSONフィールドが発生すると宣言します。ソリューション1:クラスAでフィールドファイリング1を削除します。ソリューション2:JSONの @expose Annotationを使用して、クラスA MessageText @exposeに印刷するフィールドFiled1を追加します。その後、親クラスで注釈なしでfield1は除外されます。
gson g = new gsonbuilder()。
5.属性名を変更します
3。例を使用してください:
Import java.lang.reflect.type; Import java.sql.timestamp; Import java.text.dateformat; import java.text.simpledateformat; Import java.util.arraylist; import java.util.util.date; Import java.util.list; import com.google.gson.gson com.google.gson.gsonbuilder; Import com.google.gson.jsondeserializationContext; import com.google.gson.jsondeserializer; Import com.google.gson.jsonelement; Import com.google.gson.jsonparseexceptive; Import com.google.gson.jsonpriviit; com.google.gson.jsonserializationContext; Import com.google.gson.jsonserializer; Import com.google.gson.relect.typetoken; public static void main(string [] args){// gson gson = new gson(); //タイプGSON GSON = new GSONBUILDER()。RegisterTyPeadapter(Timestamp.Class、new Timestamptypeadapter())のプロパティのフォーマット変換の設定。 list <person> persons = new ArrayList <serson>(); for(int i = 0; i <10; i ++){person p = new person(); P.SetName( "name" + i); P.Setage(i * 5); P.SetInSertTime(新しいタイムスタンプ(System.CurrentTimemillis())); persons.add(p); } string str = gson.tojson(persons); System.out.println(str); List <Person> PS = GSON.FROMJSON(str、new typetoken <list <person >>(){}。getType()); for(int i = 0; i <ps.size(); i ++){person p = ps.get(i); System.out.println(p.toString()); } system.out.println(new Timestamp(system.currenttimemillis())); }} class person {private string name;プライベートインクエイジ;プライベートタイムスタンプインサートタイム。 public string getName(){return name; } public void setName(string name){this.name = name; } public int getage(){return age; } public void Setage(int age){this.age = age; } public Timestamp getInsertTime(){return InsertTime; } public void setinSertTime(Timestamp InsertTime){this.inserttime = insertTime; } @Override public String toString(){return name + "/t" + age + "/t" + insertTime; }} //シリアル化と脱介入インターフェイスクラスタイムスタンプピープリーダーはJsonserializer <timestamp>、jsondeserializer <timestamp> {public jsonelement serialize(timestamp src、type arg1、jsonserializationcontext arg2){dateformat = new simpledatemateformat( "yimmddddddddddddddddddddddddddddde HH:MM:SS:SS "); string dateformatastring = format.format(new Date(src.getTime()));新しいjsonprimitive(dateformatasstring)を返します。 } public Timestamp Deserialize(jsonelement json、Type Typeoft、jsondeserializationcontextコンテキスト)jsonparseexception {if(!(json instanceof jsonprimitive)){throw new jsonparseexception( "日付は文字列値である必要があります); } try {dateformat format = new SimpledateFormat( "yyyy-mm-dd hh:mm:ss:ss");日付date =(date)format.parse(json.getasstring());新しいタイムスタンプを返します(date.getTime()); } catch(Exception e){新しいJSonParseException(e); }}}