天天看點

android将字元串轉化為json,将string轉換為JsonArray「建議收藏」

大家好,又見面了,我是你們的朋友全棧君。

隻是在這裡混合另一種方法,我想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