zoukankan      html  css  js  c++  java
  • java-序列化

    JSON字符串转换为JAVA 对象

    例:

    JSONObject jsStr = JSONObject.parseObject(topicInfo);
    TopicExt topicExt =  (TopicExt)JSONObject.toJavaObject(jsStr, TopicExt.class);

    序列化对象

    ObjectOutputStream 类用来序列化一个对象,如下的 SerializeDemo 例子实例化了一个 Employee 对象,并将该对象序列化到一个文件中。

    该程序执行后,就创建了一个名为 employee.ser 文件。该程序没有任何输出,但是你可以通过代码研读来理解程序的作用。

    注意: 当序列化一个对象到文件时, 按照 Java 的标准约定是给文件一个 .ser 扩展名。

     public static void main(String [] args)
       {
          Employee e = new Employee();
          e.name = "Reyan Ali";
          e.address = "Phokka Kuan, Ambehta Peer";
          e.SSN = 11122333;
          e.number = 101;
          try
          {
             FileOutputStream fileOut =
             new FileOutputStream("/tmp/employee.ser");
             ObjectOutputStream out = new ObjectOutputStream(fileOut);
             out.writeObject(e);
             out.close();
             fileOut.close();
             System.out.printf("Serialized data is saved in /tmp/employee.ser");
          }catch(IOException i)
          {
              i.printStackTrace();
          }
       }

    反序列化对象

    下面的 DeserializeDemo 程序实例了反序列化,/tmp/employee.ser 存储了 Employee 对象。

     public static void main(String [] args)
       {
          Employee e = null;
          try
          {
             FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
             ObjectInputStream in = new ObjectInputStream(fileIn);
             e = (Employee) in.readObject();
             in.close();
             fileIn.close();
          }catch(IOException i)
          {
             i.printStackTrace();
             return;
          }catch(ClassNotFoundException c)
          {
             System.out.println("Employee class not found");
             c.printStackTrace();
             return;
          }
          System.out.println("Deserialized Employee...");
          System.out.println("Name: " + e.name);
          System.out.println("Address: " + e.address);
          System.out.println("SSN: " + e.SSN);
          System.out.println("Number: " + e.number);
        }
  • 相关阅读:
    【转】23种设计模式详解
    JavaScript 中的对象引用
    iOS网络请求之NSURLSession
    学习编程是否做笔记的思考
    汇编语言——统计一个字符串中的大写字母、小写字母、数字和其他字符的个数,并显示
    windows7 64位如何调出debug
    Code:Blocks编写后出现如下错误
    iOS中Git的使用
    任意定义一个二维数组,实现矩阵的转置——java
    将八进制数转换为十进制数——java
  • 原文地址:https://www.cnblogs.com/lijianda/p/8962800.html
Copyright © 2011-2022 走看看