json.parseObjectは、JSON文字列を対応するオブジェクトに変換します。 json.tojsonstringは、オブジェクトをjson文字列に変換します。フロントエンドとバックエンド間の伝送プロセスでは、JSON文字列が非常に一般的に使用されます。ここに機能を紹介しません。これら2つの方法の使用を理解するのに役立つアプリケーションの小さな例を紹介します。
最初にMavenを使用してFastJsonを紹介します
<?xml version = "1.0" encoding = "utf-8"?> <project xmlns = "http://maven.apache.org/pom/4.0.0" xmlns:xsi = "http://www.w3.org/2001/xmlschema-instance <http://www.w3.org/2001 xsi:schemalocation = "http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.0.sdsd"> <modeleversion> 4.0.0 </modelversion> <artifidid> </groupidid> </groupid> <バージョン> 1.0-Snapshot </version> <properties> <fastjson_version> 1.2.28 </fastjson_version> </properties> <dependencies> <依存関係> com.alibaba </groupid> <artifactid> fastjson </artifactid> <バージョン> $ {eductjson_version>>>>>>>>>>>>>>>>>>>>>>>>> sopention以下に示すように、モデルクラス、従業員、および4つのプロパティを定義します。
パッケージjsontest; import java.util.date;/** * @author wujiang * @version 1.0.0。 * @date 2017/4/30 */public classスタッフ{private string name;民間整数年齢;プライベートストリングセックス;プライベートデートの誕生日; // getter and setter method @override public string toString(){return "stuff {" + "name = '" + name +'/'' + "、age =" + age + "、sex = '" + sex +'/'' + "、誕生日=" +誕生日 + '}'; }}OK、次のステップ、json.parseobjectおよびjson.tojsonstringメソッドをテストします。ここでは、JSON文字列に電話を故意に追加し、スタッフの誕生日を追加して、出力オブジェクトにどのような変更が起こるかを確認します。
パッケージjsontest; import com.alibaba.fastjson.json;/** * @author wujiang * @version 1.0.0。 * @date 2017/4/30*/public class jsontest {public static void main(string [] args){/*** json stringはオブジェクトに変換されます*/string jsonstring = "{name: 'antony'、 'antony:' 12 '、sex:' male '、電話:' 88888 '}";スタッフスタッフ= json.parseObject(jsonstring、staff.class); system.out.println(stuff.tostring()); / ***オブジェクトはjson文字列に変換されます*/ string jsonstr = json.tojsonstring(stuff); System.out.println(jsonstr); }}出力結果
スタッフ{name = 'antony'、age = 12、sex = 'male'、bashided = null} {"age":12、 "name": "antony"、 "sex": "male"} //出力結果が// {"age": "12"、 "name": "antony"、 "bale": "bale": "male": "male": "male"json.parseObjectの場合、同じ名前の属性が入力されます。 JSON文字列に存在しないプロパティの場合、モデルクラスの一部はヌルになります。モデルクラスに存在しないプロパティとJSON文字列の一部の場合、処理は行われません。
json.tojsonstringについては、もっと言う必要はありません。
たとえば、アプリケーションのシナリオについては、ユーザーがWeChatの公式アカウントにログインしたときに、WeChatの公式RESTFULインターフェイスに電話して、すべてのユーザーの情報のJSON文字列を取得し、クラスを書き込みます(クラスに必要な情報をカプセル化します)。たとえば、次の擬似コード
string s = httprequest.sendget( "https://api.weixin.qqq.com/sns/oauth2/access_token"、 "appid =" + appid + "&secret =" + "&code =" + code + "&grant_type = authorizerization return rertunturn rertunturn rertunturnのユーザー化json.parseobject(s、userauthorizationreturn.class);
上記はすべて、この記事のコンテンツ全体です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。