GVKun编程网logo

java中实体类和JSON对象之间相互转化(java中实体类和json对象之间相互转化吗)

15

如果您想了解java中实体类和JSON对象之间相互转化和java中实体类和json对象之间相互转化吗的知识,那么本篇文章将是您的不二之选。我们将深入剖析java中实体类和JSON对象之间相互转化的各个

如果您想了解java中实体类和JSON对象之间相互转化java中实体类和json对象之间相互转化吗的知识,那么本篇文章将是您的不二之选。我们将深入剖析java中实体类和JSON对象之间相互转化的各个方面,并为您解答java中实体类和json对象之间相互转化吗的疑在这篇文章中,我们将为您介绍java中实体类和JSON对象之间相互转化的相关知识,同时也会详细的解释java中实体类和json对象之间相互转化吗的运用方法,并给出实际的案例分析,希望能帮助到您!

本文目录一览:

java中实体类和JSON对象之间相互转化(java中实体类和json对象之间相互转化吗)

java中实体类和JSON对象之间相互转化(java中实体类和json对象之间相互转化吗)

在需要用到JSON对象封装数据的时候,往往会写很多代码,也有很多复制粘贴,为了用POJO的思想我们可以装JSON转化为实体对象进行操作

package myUtil;
 
import java.io.IOException;
 
import myProject.Student;
import myProject.StudentList;
 
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
 * 实体类和JSON对象之间相互转化(依赖包jackson-all-1.7.6.jar、jsoup-1.5.2.jar)
 * @author wck
 *
 */
public class JSONUtil {
  /**
   * 将json转化为实体POJO
   * @param jsonStr
   * @param obj
   * @return
   */
  public static<T> Object JSONToObj(String jsonStr,Class<T> obj) {
    T t = null;
    try {
      ObjectMapper objectMapper = new ObjectMapper();
      t = objectMapper.readValue(jsonStr,obj);
    } catch (Exception e) {
      e.printstacktrace();
    }
    return t;
  }
  /**
   * 将实体POJO转化为JSON
   * @param obj
   * @return
   * @throws JSONException
   * @throws IOException
   */
  public static<T> JSONObject objectToJson(T obj) throws JSONException,IOException {
    ObjectMapper mapper = new ObjectMapper(); 
    // Convert object to JSON string 
    String jsonStr = "";
    try {
       jsonStr = mapper.writeValueAsstring(obj);
    } catch (IOException e) {
      throw e;
    }
    return new JSONObject(jsonStr);
  }
  public static void main(String[] args) throws JSONException,IOException {
    JSONObject obj = null;
    obj = new JSONObject();
    obj.put("name","213");
    obj.put("age",27);
    JSONArray array = new JSONArray();
    array.put(obj);
    obj = new JSONObject();
    obj.put("name","214");
    obj.put("age",28);
    array.put(obj);
    Student stu = (Student) JSONToObj(obj.toString(),Student.class);
    JSONObject objList = new JSONObject();
    objList.put("student",array);
    System.out.println("objList:"+objList);
    StudentList stuList = (StudentList) JSONToObj(objList.toString(),StudentList.class);
    System.out.println("student:"+stu);
    System.out.println("stuList:"+stuList);
    System.out.println("#####################################");
    JSONObject getobj = objectToJson(stu);
    System.out.println(getobj);
  }
}

以上所述就是本文的全部内容了,希望大家能够喜欢。

Android JSON数据与实体类之间的相互转化(GSON的用法)

Android JSON数据与实体类之间的相互转化(GSON的用法)

这篇文章就是示范如何用GSON把JSON数据与实体类进行相互转化,需要用到gson-2.3.1.jar这个包。直接贴代码了:

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.Typetoken;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class MainActivity extends Activity implements OnClickListener {
  private Button bt_shitiToJson;
  private Button bt_jsonToShiti;
  private Button bt_jsonToList;
  private Button bt_listToJson;

  private Gson gson;
  private GsonBuilder builder;

  private Person person;

  private String jsonTest,jsonListTest;
  private List<Person> persons;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();

  }

  private void init() {
    //寻找控件
    bt_shitiToJson=(Button) findViewById(R.id.bt_shitiToJson);
    bt_jsonToShiti=(Button) findViewById(R.id.bt_jsonToShiti);
    bt_listToJson=(Button) findViewById(R.id.bt_listToJson);
    bt_jsonToList=(Button) findViewById(R.id.bt_jsonToList);
    //增加点击事件
    bt_shitiToJson.setonClickListener(this);
    bt_jsonToShiti.setonClickListener(this);
    bt_listToJson.setonClickListener(this);
    bt_jsonToList.setonClickListener(this);

    //这两句代码必须的,为的是初始化出来gson这个对象,才能拿来用
    builder=new GsonBuilder();
    gson=builder.create();

    //先制造出一个"人",第一个按钮点击的时候要用到
    person=new Person();
    person.setName("张三");
    person.setAge(20);
    person.setTall(160);

  }

  @Override
  public void onClick(View v) {
    switch(v.getId()){
    case R.id.bt_shitiToJson://实体类转换为json数据
      jsonTest=gson.toJson(person,Person.class);
      Log.e("test",jsonTest);
      //打印出来结果为
      // {"name":"张三","age":20,"tall":160}

      break;
    case R.id.bt_jsonToShiti://json数据转换为实体类
      Person p=gson.fromJson(jsonTest,p.getName()+" "+p.getAge()+" "+p.getTall());
      //打印出来结果为
      //张三 20 160

      break;
    case R.id.bt_listToJson://存储实体类的集合转换为json数据集合
      //手动制造一个存有三人信息的集合,以便进行测试
      persons=new ArrayList<Person>();
      for(int i=0;i<3;i++){
        Person p1=new Person();
        p1.setName("李四"+i);
        p1.setAge(23+i);
        p1.setTall(165+i);
        persons.add(p1);
      }
      //persons被制造好了,现在开始测试
      //需要注意的是这里的Type导入的是java.lang.reflect.Type的包
      //Typetoken导入的是 com.google.gson.reflect.Typetoken的包
      Type type=new Typetoken<List<Person>>(){}.getType();
      jsonListTest=gson.toJson(persons,type);
      Log.e("test",jsonListTest);
      //打印出来的数据
// [{"name":"李四0","age":23,"tall":165},{"name":"李四1","age":24,"tall":166},{"name":"李四2","age":25,"tall":167}]
      break;
    case R.id.bt_jsonToList://json数据的集合转换为存储实体类的集合
      List<Person> p2=new ArrayList<Person>();
      Type type1=new Typetoken<List<Person>>(){}.getType();
      p2=gson.fromJson(jsonListTest,type1);
      Log.e("test",p2.size()+"");
      //打印了存储实体类集合的大小,不用看啦,,大小肯定是3
      //打印结果
      //3
      break;

    }

  }
}

Person这个类:

public class Person {
//人的名称
private String name;
//人的年龄
private int age;
//人的身高
private int tall;
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 int getTall() {
  return tall;
}
public void setTall(int tall) {
  this.tall = tall;
}

}

activity_main.xml文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  >

  <TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="使用GSON进行JSON数据的处理"
    android:textColor="#353535"
    android:textSize="17sp"
    android:textandroid:layout_marginTop="20dip" />

  <Button
    android:id="@+id/bt_shitiToJson"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="实体类转换为JSON数据" 
    android:layout_marginTop="10dip" />

  <Button
    android:id="@+id/bt_jsonToShiti"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="JSON数据转换成实体类"
    android:onClick="bt_create_student"
    android:layout_marginTop="10dip" />
  <Button
    android:id="@+id/bt_listToJson"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="存有实体类的集合转换为JSON数据集合"
    android:layout_marginTop="10dip" />

  <Button
    android:id="@+id/bt_jsonToList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="JSON数据集合转换为存有实体类的集合"
     android:layout_marginTop="10dip" />



</LinearLayout>

这个DEMO太简单了,估计没有人会导入到eclipse看结果吧,如果导入的话,使用的时候需要注意一点,就是点第一个按钮才能开始点第二个按钮,点第三个按钮才能开始点第四个按钮,不然会报错,原因我就不解释了,在代码里自己看吧。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

datatable与实体类之间相互转化的几种方法

datatable与实体类之间相互转化的几种方法

#region DataTable转换成实体类
 
 
        /// <summary>
        /// 填充对象列表:用DataSet的第一个表填充实体类
        /// </summary>
        /// <param name="ds">DataSet</param>
        /// <returns></returns>
        public List<T> FillModel(DataSet ds)
        {
            if (ds == null || ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0)
            {
                return null;
            }
            else
            {
                return FillModel(ds.Tables[0]);
            }
        }
 
 
        /// <summary>  
        /// 填充对象列表:用DataSet的第index个表填充实体类
        /// </summary>  
        public List<T> FillModel(DataSet ds, int index)
        {
            if (ds == null || ds.Tables.Count <= index || ds.Tables[index].Rows.Count == 0)
            {
                return null;
            }
            else
            {
                return FillModel(ds.Tables[index]);
            }
        }
 
 
        /// <summary>  
        /// 填充对象列表:用DataTable填充实体类
        /// </summary>  
        public List<T> FillModel(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return null;
            }
            List<T> modelList = new List<T>();
            foreach (DataRow dr in dt.Rows)
            {
                //T model = (T)Activator.CreateInstance(typeof(T));  
                T model = new T();
                for (int i = 0; i < dr.Table.Columns.Count; i++)
                {
                    PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
                    if (propertyInfo != null && dr[i] != DBNull.Value)
                        propertyInfo.SetValue(model, dr[i], null);
                }
 
 
                modelList.Add(model);
            }
            return modelList;
        }
 
 
        /// <summary>  
        /// 填充对象:用DataRow填充实体类
        /// </summary>  
        public T FillModel(DataRow dr)
        {
            if (dr == null)
            {
                return default(T);
            }
 
 
            //T model = (T)Activator.CreateInstance(typeof(T));  
            T model = new T();
 
 
            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
                if (propertyInfo != null && dr[i] != DBNull.Value)
                    propertyInfo.SetValue(model, dr[i], null);
            }
            return model;
        }
 
 
        #endregion
 
 
        #region 实体类转换成DataTable
 
 
        /// <summary>
        /// 实体类转换成DataSet
        /// </summary>
        /// <param name="modelList">实体类列表</param>
        /// <returns></returns>
        public DataSet FillDataSet(List<T> modelList)
        {
            if (modelList == null || modelList.Count == 0)
            {
                return null;
            }
            else
            {
                DataSet ds = new DataSet();
                ds.Tables.Add(FillDataTable(modelList));
                return ds;
            }
        }
 
 
        /// <summary>
        /// 实体类转换成DataTable
        /// </summary>
        /// <param name="modelList">实体类列表</param>
        /// <returns></returns>
        public DataTable FillDataTable(List<T> modelList)
        {
            if (modelList == null || modelList.Count == 0)
            {
                return null;
            }
            DataTable dt = CreateData(modelList[0]);
 
 
            foreach (T model in modelList)
            {
                DataRow dataRow = dt.NewRow();
                foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
                {
                    dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
                }
                dt.Rows.Add(dataRow);
            }
            return dt;
        }
 
 
        /// <summary>
        /// 根据实体类得到表结构
        /// </summary>
        /// <param name="model">实体类</param>
        /// <returns></returns>
        private DataTable CreateData(T model)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);
            foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
            {
                dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
            }
            return dataTable;
        }
 
 
        #endregion

  

---------------------
来源:CSDN
原文:https://blog.csdn.net/a11112244444/article/details/78921200
版权声明:本文为博主原创文章,转载请附上博文链接!

fastJson javaBean和JSON对象相互转换

fastJson javaBean和JSON对象相互转换

fastjson的作用就是把java 对象转化为字符串,把字符串转化为java对象,然后方便进行后续的逻辑处理。

java对象和json互相转换都是通过JSON对象操作的:

JavaBean bean = JSON.toJSONString(javaBean);
String str = JSON.pase(str, JaveBean);

JSONObject可以当做map处理,可以通过map或者实体类;来初始化

初始化方式1:
JSONObject json= new JSONObject();
json.put("1","1");
json.put("1","1");
json.put("1","1");

方式2:
Map<String, Object> map = new HashMap<>();        
map.put("name", "1");
map.put("age", 12);
map.put("birthday", "1999-20-03");
JSONObject json = new JSONObject(zhangsan);
 
方式3:
User user=new User();
user.put("name", "2");
user.put("age", 11);
user.put("birthday", "1999-20-03");
JSONObject json = new JSONObject(zhangsan);

JSONArray

获取JSONObject
JSONObject json = (JSONObject)jsonArray.get(i);
JSONObject json = jsonArray.getJSONObject(i);

 

What''s more ?

That''s all !

FastJson JSON对象及JavaBean之间的相互转换

FastJson JSON对象及JavaBean之间的相互转换

一、解析Json 将Json 转换成java bean

 

示例1:JSON格式字符串与javaBean之间的转换。

json字符串与javaBean之间的转换推荐使用 TypeReference<T> 这个类,使用泛型可以更加清晰

/**
     * json字符串-简单对象与JavaBean_obj之间的转换
     */
    public static void testJSONStrToJavaBeanObj(){

        Student student = JSON.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {});

        //Student student1 = JSONObject.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {});
//因为JSONObject继承了JSON,所以这样也是可以的

    }

示例2.2-json字符串-数组类型与javaBean之间的转换

public static void testJSONStrToJavaBeanList(){
        
        ArrayList<Student> students = JSON.parseObject(JSON_ARRAY_STR, new TypeReference<ArrayList<Student>>() {});


        ArrayList<Student> students1 = JSONArray.parseObject(JSON_ARRAY_STR, new TypeReference<ArrayList<Student>>() {});

//因为JSONArray继承了JSON,所以这样也是可以的 }

 

二、对象转Json

C2Result c1 = new  C2Result();
c1.setErrorCode("0");
c1.setErrorText("成功");
String result = JSONObject.toJSON(c1).toString();

 

  List 转 JSONArray []

 JSONArray.fromObject(vos).toString();

 

关于java中实体类和JSON对象之间相互转化java中实体类和json对象之间相互转化吗的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于Android JSON数据与实体类之间的相互转化(GSON的用法)、datatable与实体类之间相互转化的几种方法、fastJson javaBean和JSON对象相互转换、FastJson JSON对象及JavaBean之间的相互转换等相关内容,可以在本站寻找。

本文标签: