用途
- 测试String对象与byte数组转换方式
- 测试Json对象与byte数组转换方式
源代码
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Date;
import com.alibaba.fastjson.JSONObject;
public class TestStringBytes {
public static void main(String[] args) {
System.out.println("测试string与 byte数组转换");
testStringBytesConvert("abc123张三");
System.out.println("测试json与byte数组转换");
testJsonByteConvert();
}
public static void testStringBytesConvert(String s) {
try {
byte[] ba = s.getBytes("UTF-8");
String s_new = new String(ba, "UTF-8");
System.out.println("原始字符串:\t" + s);
System.out.println("byte数组地址:\t" + ba);
System.out.println("输出byte数组:\t" + Arrays.toString(ba));
System.out.println("转换为字符串:\t" + s_new);
System.out.println("---------------------------");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static void testJsonByteConvert() {
JSONObject json = new JSONObject();
json.put("id", 1);
json.put("name", "张三");
json.put("birthday", new Date());
json.put("age", 36);
testStringBytesConvert(json.toString());
}
}
输出结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9938d63c79d7539caa05ac5aff033726.png)