zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

android将字符串转化为json,将string转换为JsonArray「建议收藏」

Android转换JSONJSON string 建议 收藏 字符串
2023-06-13 09:11:41 时间

大家好,又见面了,我是你们的朋友全栈君。

只是在这里混合另一种方法,我想build议看看Gson 。 Gson是一个使Java对象序列化和反序列化的库。 例如,用你的string,你可以这样做:

// Declare these somewhere that is on the classpath public class ArrayItem{ public int id; public double att1; public boolean att2; } public class Container{ public List myArray; } // In your code Gson gson = new Gson(); Container container = gson.fromJson(json, Container.class); for(ArrayItem item : container.myArray){ System.out.println(item.id); // 1, 2, 3 System.out.println(item.att1); // 14.2, 13.2, 13.0 System.out.println(item.att2); // false, false, false }

同样,你也可以很容易地倒退。

String jsonString = gson.toJson(container); // jsonString no contains something like this: // {“myArray”:[{“id”:1,”att1″:14.2,”att2″:false},{“id”:2,”att1″:13.2,”att2″:false},{“id”:3,”att1″:13.0,”att2″:false}]}

使用像Gson提供的主要好处是你现在可以默认使用所有的Javatypes检查,而不必自己pipe理属性名称和types。 它也允许你做一些奇特的东西,如复制types层次结构,使pipe理大量的JSON消息快照。 它适用于Android,而且它本身很小,不需要额外的依赖。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/151469.html原文链接:https://javaforall.cn