Json
Compare to XML, JSON is much smaller in size.T
package com.minte9.collections.json;
import static org.junit.Assert.assertEquals;
import org.json.JSONObject;
import org.junit.Test;
public class JsonTest {
@Test public void json() {
String s = "{message:{type:feed,timestamp:1},error:0}";
JSONObject obj = new JSONObject(s);
assertEquals("feed", obj.getJSONObject("message").getString("type"));
// passed
assertEquals(0, obj.getInt("error"));
// passed
}
}
Translate
Custom formats can be easily transtated to Json.
/**
* Translate custom formats to json for easy parsing.
*/
package com.minte9.collections.json;
import org.json.JSONObject;
public class Translate {
public static void main(String[] args) {
//String s = "{message:{type:feed,timestamp:1},error:0}"; // json
String s = "{message={type=feed|timestamp=1},error=0}"; // not a json
JSONObject obj;
s = translate(s);
obj = new JSONObject(s);
System.out.println(
obj.getJSONObject("message").getString("type") // feed
);
System.out.println(
obj.getInt("error") // 0
);
}
public static String translate(String s) {
s = s.replaceAll("([^={}|]+)=", "$1="); // add quotes to keys
s = s.replaceAll("=([^={}|]+)", "=$1"); // add quotes to values
s = s.replace("|", ",").replace("=", ":");
// System.out.println(s);
return s;
}
}
Loop
To parse json array, use for-each loop with getJSONArray() method.
/**
* Use getJSONArray() in order to loop an json
*/
package com.minte9.collections.json;
import org.json.JSONArray;
import org.json.JSONObject;
public class Loop {
public static void main(String[] args) {
String str = "{"
+ "orders: ["
+ "{sym:goog,amount:100,error:1},"
+ "{sym:msft,amount:200,error:0}"
+ "], error:0" +
"}";
JSONObject obj = new JSONObject(str);
JSONArray orders = obj.getJSONArray("orders");
//System.out.println(orders);
for(Object item : orders) {
JSONObject order = (JSONObject) item; // Look Here
System.out.println(""
+ order.getString("sym")
+ ":"
+ order.getInt("error")
);
// goog:1
// msft:0
}
}
}
Last update: 447 days ago