Back to Home

Gson

Gson also supports object annotations:

  • @Expose - An annotation that indicates this member should be exposed for JSON serialization or deserialization.
  • @SerializedName(“isMessagePromotion”) - the Json tag to be used

Simple Json

String data = org.apache.commons.io.FileUtils.readFileToString(new File("/home/richard/workspace/workspace_strim/JsonParsing/src/data.json"));
  	Map obj= (Map)JSONValue.parse(data); // parse json data
		System.out.println( obj.get("aaData") ); // extract object with associated array list 
		JSONArray arr =  (JSONArray) obj.get("aaData");
 
		comp.setAttribute("stb", arr);

Simple Json seems much more straight forward generating Json also:

public class SimpleJson {
	//data section
	String connectStatus = "everything ok";
	Date lastAlarm = new Date();
	ArrayList connectorData = new ArrayList();
 
	public void addConnectorData(String queue, Long connector){
		Map map =new LinkedHashMap();
		map.put("queue", queue);
		map.put("connector", connector);
		connectorData.add(map);
 
	}
 
 
	public static void main(String[] args) throws Exception{
		SimpleJson sj = new SimpleJson();
		sj.addConnectorData("queue1", 1L);
 
		JSONObject obj = new JSONObject();
		obj.put("status", sj.connectStatus);
		obj.put("lastAlarm", sj.lastAlarm);					
		obj.put("connectorData", sj.connectorData);
 
		// output the result 
		StringWriter out = new StringWriter();
		obj.writeJSONString(out);
		String jsonText = out.toString();
		System.out.print(jsonText);
	}

Will generate

{"status":"everything ok","lastAlarm":Tue Apr 01 19:03:46 BST 2014,"connectorData":[{"queue":"queue1","connector":1}]}

Jackson

  • Jackson - (default in mule ) for the data value:

{“Get_ClientID_By_ClientIDResult”:“2”}

ObjectMapper mapper = new ObjectMapper();
Map<String,Object> userData = mapper.readValue(result.getPayloadAsString() , Map.class);
System.err.println("Json data: " + userData.get("Get_ClientID_By_ClientIDResult") );

Jackson for Json

package org.bskyb.json;
import java.util.ArrayList;
import java.util.Date;

import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.ObjectMapper;

@JsonAutoDetect
public class ActiveMqResult {
	
	/**
	 * Json Properties with defined names 
	 */
	@JsonProperty("status")
	public String connectorStatus = "";
	@JsonProperty("connectorData")
	ArrayList <ConnectorData> queueData = new ArrayList<ConnectorData>();
	//@JsonSerialize(using = CustomJsonDateSerializer.class)
	@JsonProperty("lastAlarm")
	Date lastAlarm = new Date();
	
	public void add(String queue, Long count, Long depth){
		ConnectorData cd = new ConnectorData(queue, count, depth);
		queueData.add(cd);
	}
	
	@JsonAutoDetect
	public class ConnectorData{
		@JsonProperty("queue")
		String queue;
		@JsonProperty("count")
		Long count;
		@JsonProperty("qDepth")
		Long queueDepth;
		
		ConnectorData(String queue, Long count, Long depth){
			this.queue = queue;
			this.count = count;
			this.queueDepth = depth;
		}
				
	}
	
	public static void main(String [] args ) throws Exception{
		ActiveMqResult amr = new ActiveMqResult();
		amr.connectorStatus = "Everythign is ok";
		amr.add("queue1", 1L, 1L);
		ObjectMapper mapper = new ObjectMapper();
		mapper.writeValue(System.out, amr);		
		
	}
} 

This generates

{"lastAlarm":1396374425810,"status":"Everythign is ok","connectorData":[{"queue":"queue1","count":1,"qDepth":1}]}

Mongo BSONObject

Mongo uses a Binary BSONObject

Fast Json

Claimed to be one of the fastest json parsers

JsonPath - Jayway JsonPath

JsonPath can be used to extract data for Json

    testCompile 'com.jayway.jsonpath:json-path:2.4.0'
JsonPath.parse(line).read("\$.item.productDetail.description")

Note by default jayway will throw an exception on missing paths. This can be suppressed with:

  Configuration config = Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS)
  // and added to the parse as a config option 
  JsonPath.parse(line, config ).read("\$.item.productDetail.description")

Jayway will also do it's best to cast to the destination type JSONObject, String .. perhaps date and integer

JSONObject item = JsonPath.parse(line).read("\$.item")

jsonPath can use the object mapping of your choice Jackson, gson etc. depending on your confiuration

static {
        Configuration.setDefaults(new Configuration.Defaults() {
            private final JsonProvider jsonProvider = new JacksonJsonProvider();
            private final MappingProvider mappingProvider = new JacksonMappingProvider();
            private final Set<Option> options = EnumSet.noneOf(Option.class);

            public JsonProvider jsonProvider() {
                return jsonProvider;
            }

            @Override
            public MappingProvider mappingProvider() {
                return mappingProvider;
            }

            @Override
            public Set<Option> options() {
                return options;
            }
        });
    }
    

Minimal Json

lightweight: object representation with minimal memory footprint (e.g. no HashMaps)

 
json.txt · Last modified: 2017/11/23 09:15 by root
 
RSS - 200 © CrosswireDigitialMedia Ltd