Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Gson to convert strings to JsonObject and JsonArray

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "how to use Gson to convert strings into JsonObject and JsonArray". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Gson converts strings to JsonObject and JsonArray, both using Gson to process.

1. Convert bean to Json string:

Public static String beanToJSONString (Object bean) {return new Gson () .toJson (bean);}

two。 Convert a Json string to an object:

Public static Object JSONToObject (String json,Class beanClass) {Gson gson = new Gson (); Object res = gson.fromJson (json, beanClass); return res;}

Note: the converted object is forged before use: for example, bean bean1 = (bean) FormatUtil.JSONToObject (json, bean.class)

3. Convert a Json string to a JsonObject object:

JsonObject returnData = new JsonParser () .parse (jsonstr) .getAsJsonObject ()

4. Parsing Json strings of type JsonArray into object methods

Gson gson = new Gson (); JsonParser parser = new JsonParser (); JsonArray Jarray = parser.parse (jstring). GetAsJsonArray (); ArrayList lcs = new ArrayList (); for (JsonElement obj: Jarray) {channelSearchEnum cse = gson.fromJson (obj, channelSearchEnum.class); lcs.add (cse);}

Or

String json = "[{\" username\ ":\" test\ "}, {\" username\ ":\" test2\ "}]"; System.out.println (new JsonParser (). Parse (json). GetAsJsonArray (). Get (0). GetAsJsonObject (). Get ("username"). GetAsString ())

5. Gets the JsonArray object corresponding to the specified key value in JsonObject:

String json= "{\" pids\ ": [\" 1\ ",\" 2\ ",\" 3\ "]}"; System.out.println (new JsonParser (). Parse (json). GetAsJsonObject (). GetAsJsonArray ("pids"). Get (0). GetAsString (); JSONObject and JSON transfer each other

Purpose of use

At present, most of the data interactions are transmitted by JSON strings, and the main formats are

{"age": "22", "name": "Li Si"}

[{"age": "21", "name": "Zhang San"}]

The most common application scenarios are front-end docking and third-party platform document docking. The conversion usage is shown below.

Jar is introduced, where the com.alibaba.fastjson version of jar package com.alibaba fastjson 1.1.31 is introduced to establish the test class object class Student {private String name; private String age; public String getName () {return name;} public void setName (String name) {this.name = name } public String getAge () {return age;} public void setAge (String age) {this.age = age;}} conversion

1. Transfer object to JSON

Student stu1 = new Student (); stu1.setName (Zhang San); stu1.setAge (21); String stu1Json = JSONObject.toJSONString (stu1)

Output:

{"age": "21", "name": "Zhang San"}

2. JSON to object

Student stu1to = JSON.parseObject (stu1Json, Student.class); System.out.println ("json to object:"); System.out.println (stu1to); System.out.println (stu1to.getName ()); System.out.println (stu1to.getAge ())

Output:

Json to object:

Student@2aae9190

Zhang San

twenty-one

Note: JSON key name should correspond to object attribute name

3. Convert the object array to JSON

Student stu2 = new Student (); stu2.setName (Li Si); stu2.setAge ("22"); List list = new ArrayList (); list.add (stu1); list.add (stu2); String listJson = JSONObject.toJSONString (list); System.out.println (listJson)

Output:

[{"age": "21", "name": "Zhang San"}, {"age": "22", "name": "Li Si"}]

4. JSON to object array

List studentList = JSON.parseArray (listJson, Student.class); for (Student student: studentList) {System.out.println (student.getName ());}

Output:

Json array format conversion object

Zhang San

Li Si

5. JSON multi-level combination, which is suitable for request document transmission parameters.

JSONObject jsona = new JSONObject (); jsona.put ("number", "1"); JSONObject jsonb = new JSONObject (); jsonb.put ("listMap", list); JSONObject jsonAll = new JSONObject (); jsonAll.put ("jsona", jsona); jsonAll.put ("jsonb", jsonb); String jsonAllStr = JSONObject.toJSONString (jsonAll); System.out.println (jsonAllStr)

Output:

{"jsona": {"number": "1"}, "jsonb": {"listMap": [{"age": "21", "name": "Zhang San"}, {"age": "22", "name": "Li Si"}]}}

6. Multi-level JSON combination

6.1. Get only the specified fields, followed by the sample code above

String getJsona = JSON.parseObject (jsonAllStr) .getString ("jsona"); String strjsona = JSON.parseObject (getJsona, String.class); / / specify to get the field name object information. If it is not specified for a single String, System.out.println is written as an instance ("only take jsona information"); System.out.println (strjsona)

Output:

Just take jsona information.

{"number": "1"}

6.2. Get the specified field object

String getJsonb = JSON.parseObject (jsonAllStr) .getString ("jsonb"); String getJsonbb = JSON.parseObject (getJsonb) .getString ("listMap"); / / there is a second-level package here, so you have to get it twice to convert the object array List strjsonb = JSON.parseArray (getJsonbb, Student.class); System.out.println ("only take jsonbb information"); System.out.println (strjsonb)

Output:

Just take jsonbb information.

[Student@3d04a311, Student@7a46a697]

That's all for "how to use Gson to convert strings into JsonObject and JsonArray". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report