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 assign a default value to JavaBean and convert it to Json string

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces how to assign default values to JavaBean and convert Json string related knowledge, the content is detailed and easy to understand, the operation is simple and fast, with a certain reference value, I believe that after reading this article on how to assign default values to JavaBean and transfer to Json string article will have a harvest, let's take a look.

JavaBean assigns default values and converts Json strings

Today, when finishing the dubbo interface at work, some interface parameter types are JavaBean type data, and when finishing, I want to directly sort out the JavaBean parameters in the default json format, so I think of how to convert the default values of javaBean directly into Json format data to avoid spelling json strings manually.

There is something worth optimizing in this code.

For the time being, it only supports the conversion of Java basic data types, but does not support the conversion of other javaBean object variables in javaBean, nor does it support the conversion of List/Map and other types. Later, you can think of ways to optimize it. If you have optimized code, you can share it.

Don't talk too much nonsense, just go to the code

Package com.up.util.tools; import com.google.gson.Gson; import java.lang.reflect.Field;import java.lang.reflect.Method;import java.util.Date;import java.util.HashMap;import java.util.Map; / * * Created by * * on 2017-3-29 * TIME 11:07. * / public class JavaBeanToJson {public static String toJson (Class clazz) throws Exception {Gson gson = new Gson (); String result = ""; if (clazz.equals (Map.class)) {result = clazz.getName () + "\ t" + gson.toJson (new HashMap ());} else {Object object = clazz.newInstance (); object = getBean (object) Result = clazz.getName () + "\ t" + gson.toJson (object);} return result;} private static Object getBean (T object) throws Exception {Class classType = object.getClass (); / / SqlRowSet srs = jdbcTemplate.queryForRowSet (sql); Field [] fields = classType.getDeclaredFields () / / get the fields in the object / / in each loop, re-instantiate an object of the same type as the passed object T objectCopy = (T) classType.getConstructor (new Class [] {}) .newInstance (new Object [] {}); for (int I = 0; I < fields.length; iFields +) {Field field = fields [I]; String fieldName = field.getName () Object value = null; / / decide which get method to use in the result set to get the data from the data if (field.getType (). Equals (String.class)) {value = "" depending on the field type. } else if (field.getType () .equals (int.class) | | field.getType () .equals (Integer.class)) {value = new Integer (0);} else if (field.getType () .equals (double.class) | | field.getType () .equals (Double.class)) {value = new Double (0) } else if (field.getType (). Equals (long.class) | | field.getType () .equals (Long.class)) {value = new Long (0);} else if (field.getType () .equals (Date.class)) {value = new Date () } else if (field.getType (). Equals (Object.class)) {value = new Object ();} / / get the first letter of the attribute and convert it to uppercase, corresponding to setXXX String firstLetter = fieldName.substring (0,1). ToUpperCase (); String setMethodName = "set" + firstLetter + fieldName.substring (1) If (fieldName.equals ("serialVersionUID")) {continue;} Method setMethod = classType.getMethod (setMethodName, new Class [] {field.getType ()}); setMethod.invoke (objectCopy, new Object [] {value}); / / call object's setXXX method} return objectCopy }} javaBean object and Json format string convert to each other

Generally speaking, front and back end developers interact with strings in json format, so it is necessary to convert javaBean objects into json format strings and json format strings into javaBean objects.

Here are two methods:

one。 Use the Jackson utility class

1.pom dependence

Com.fasterxml.jackson.core jackson-annotations 2.8.1 com.fasterxml.jackson.core jackson-core 2.8.6 com.fasterxml.jackson.core jackson-databind 2.8.6 junit junit 4.12

two。 Program code

Package com.john.json; import com.fasterxml.jackson.databind.ObjectMapper;import org.junit.Test; import java.io.IOException; public class TestJackson {@ Test public void testObjAndJson () throws IOException {Dog dog = new Dog (); dog.setName ("Cherry"); dog.setAge (1); dog.setFood ("Xiaomi"); / / create Jackson advanced object ObjectMapper mapper = new ObjectMapper () / / the object is converted to the corresponding json format string String json = mapper.writeValueAsString (dog); System.out.println (json); / / the json format string is converted to the corresponding object Dog dogBack = mapper.readValue (json, Dog.class); System.out.println (dogBack.getName () + "-" + dogBack.getAge () + "--+ dogBack.getFood ());}} two. Use the Gson utility class

1.pom dependence

Com.google.code.gson gson 2.2.4 junit junit 4.12

two。 Program code

Package com.john.json; import com.google.gson.Gson;import org.junit.Test; public class TestGson {@ Test public void testObjAndJson () {Dog dog = new Dog (); dog.setName ("Niu Niu"); dog.setAge (3); dog.setFood ("rice"); / / create gson object Gson gson = new Gson () / / convert the object to the corresponding json format string String dogJson = gson.toJson (dog); System.out.println (dogJson); / / json format string to the corresponding object Dog dogBack = gson.fromJson (dogJson, Dog.class); System.out.println (dogBack.getName () + "-" + dogBack.getAge () + "-" + dogBack.getFood () }} this is the end of the article on "how to assign default values to JavaBean and convert Json strings". Thank you for reading! I believe you all have a certain understanding of "how to assign default values to JavaBean and convert Json strings". If you want to learn more, you are welcome to follow the industry information channel.

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