Skip to content

Instantly share code, notes, and snippets.

@mikofski mikofski/README.md
Last active Jul 26, 2016

Embed
What would you like to do?
Using org.json in MATLAB
% download JSON.net from https://github.com/JamesNK/Newtonsoft.Json/releases
% extract into MATLAB folder
%% add assembly (assuming not registered in GAC)
asm = NET.addAssembly('%HOME%\Documents\MATLAB\Json70r1\bin\Net35\Newtonsoft.Json.dll')
%% DESERIALIZING JSON OBJECT
% using the following example:
% {"inputs":
% {"module":
% {"name": "spr-e20-435",
% "nameplate": 435
% }
% },
% {"request":
% {"startdate": [2015,1,1,1,0,0],
% "enddate": [2015,12,31,23,0,0]
% }
% }
% }
%% get source using io
str_data = fileread('path/to/file.json')
%% use Json.Convrters.DeserializeObject(str_data)
json_data = Newtonsoft.Json.JsonConvert.DeserializeObject(str_data)
inputs = json_data.GetValue('inputs')
module = inputs.GetValue('module')
name = module.GetValue('name').Value()
nameplate = module.GetValue('nameplate').Value()
startdate(1) = inputs.GetValue('request').Item(0)
startdate(2) = inputs.GetValue('request').Item(1)
startdate(3) = inputs.GetValue('request').Item(2)
startdate(4) = inputs.GetValue('request').Item(3)
startdate(5) = inputs.GetValue('request').Item(4)
startdate(6) = inputs.GetValue('request').Item(5)
%% prettyprint output
json_data.ToString()
%% SERIALIZE LINQ JSON OBJECT
% create a LINQ JObject
json_obj = Newtonsoft.Json.Linq.JObject() % create object
methodsview(json_obj) % view all methods for JObject
json_obj.Add('this', Newtonsoft.Json.Linq.JValue('that'))
json_obj.Add('foo', Newtonsoft.Json.Linq.JArray([10,20,30]))
json_obj.Add('bar', Newtonsoft.Json.Linq.JArray({'x','y','z'}))
%% prettyprint
json_obj.ToString() % pretty print
%% serialize json object
json_str = json_obj.Add('foo', Newtonsoft.Json.Linq.JArray([10,20,30]))
fid = fopen('outputfile.json')
fwrite(fid,json_str)
fclose(fid)
%% this is MATLAB, not Objective-C
%% orgJSONdemo.m
% a demo of org.json classes used in MATLAB
% NOTE: JSON.org must be on the Java classpath
%% clear workspace
clc
clear java % clear all and any java classes loaded from the dynamic path
clear import % clear all java imports
%% what version of Java JRE/JDK
version -java % display Java version (1.6 is Java Standard Edition 6)
%% simplify Java class names
import org.json.* % import all org.json classes
import java.util.HashMap % import a single class
import java.util.ArrayList % Maps and Collections are Java objects useful for JSONObjects and JSONArrays
% http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html
% http://docs.oracle.com/javase/6/docs/api/java/util/Map.html
import % display imports
%% display JSONObject methods
methods JSONObject % list methods in command window
methodsview JSONObject % window with table of methods with return type, arguments and other info
methodsview('JSONArray') % to use as function call pass a string, NOT the object constructor!
% http://www.mathworks.com/help/techdoc/matlab_prog/f10-60037.html#f10-60072
methodsview HashMap
methodsview ArrayList
%% JSONObject - constructor methods
% public JSONObject()
% Construct an empty JSONObject.
% http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject()
jo = JSONObject;jo.toString % () not required for no-arg function calls
% public JSONObject(java.lang.String source)
% Construct a JSONObject from a source JSON text string.
% http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject(java.lang.String)
source = ['{module:SunPower SPR-315-WHT-AR D,', ... use braces, {}, but quotes, "", are not necessary, spaces OK
'Voc:0.6732,', ... numbers, strings & objects are interpreted automatically, use quotes to force numbers to string, e.g. "1"
'nothing:[],', ... an empty key value is NOT OK, but empty JSONArray is OK
'blah:null,', ... a json null key value is OK, so is an empty string, which is not the same as json null
'cells:[null,TRUE,False,', ... json null, true, false are OK, case insensitive
',"",', ... an emtpy Array element is a json null, "" is an empty string, which is not the same as json null
'"c:\\Program Files","\"in quotes\"",', ... use quotes, "\\", with an characters that need to be escaped, e.g. " or \
'"http://json.org"]}']; % use quotes for forward slash, /
jo = JSONObject(source);jo.toString(4) % display with 4-space indent
% public JSONObject(JSONObject jo, java.lang.String[] names)
% Construct a JSONObject from a subset of another JSONObject.
% http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject(org.json.JSONObject, java.lang.String[])
jo = JSONObject(jo,{'module','Voc'});jo.toString(2) % cellstring is interpreted as array of strings
% public JSONObject(java.util.Map map)
% Construct a JSONObject from a Map.
% http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject(java.util.Map)
clear jo
s = struct('module',{'SunPower SPR-315-WHT-AR D','SunPower SPR-240-WHT-AR D'}, ...
'Voc',{0.6732,0.7324}, ...
'cells',{1:3,[5,6;7,8]'});
map(size(s)) = HashMap; % create a Java array of objects of empty Hash-Maps
jo(size(s)) = JSONObject; % Java arrays must have consistent signature, emtpy constructor is OK
skeys = fieldnames(s); % keys are fieldnames
sVals = struct2cell(s); % values of fields in a cell array
for n = 1:size(s,2) % loop over rows
for m = 1:size(s,1) % loop over columns
for p = 1:length(skeys) % loop over keys (structure fields)
map(n,m).put(skeys{p},sVals{p,m,n}); % map each key to its value
end
jo(n,m) = JSONObject(map(n,m));jo(n,m).toString(3) % create json object from java hash map
end
end
%% JSONObject - PUT method
% public JSONObject put(java.lang.String key, java.lang.Object value)
% Put a key/value pair in the JSONObject.
% value - An object which is the value. It should be of one of these types:
% Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONObject.NULL object.
% http://www.json.org/javadoc/org/json/JSONObject.html#put(java.lang.String, java.lang.Object)
clear jo
s = struct('module',{'SunPower SPR-315-WHT-AR D','SunPower SPR-240-WHT-AR D'}, ...
'Voc',{0.6732,0.7324}, ...
'cells',{1:3,[5,6;7,8]'});
jo(size(s)) = JSONObject; % Java arrays must have consistent signature, emtpy constructor is OK
skeys = fieldnames(s); % keys are fieldnames
sVals = struct2cell(s); % values of fields in a cell array
for n = 1:size(s,2) % loop over rows
for m = 1:size(s,1) % loop over columns
for p = 1:length(skeys) % loop over keys (structure fields)
jo(n,m).put(skeys{p},sVals{p,m,n}); % map each key to its value
end
jo(n,m).toString(5)
end
end
jo(1,1).put('module',{}) % remove that key form the json object
jo(1,1).put('module',[]) % put an emtpy json array
jo(1,1).put('module',[{}]) %#ok<NBRAK> % remove that key form the json object
jo(1,1).put('module','') % put an emtpy json array
jo(1,1).put('module',{[]}) % put a java object array with a single empty MATLAB array
jo(1,1).put('module',{''}) % put a java string array with a single empty java string
%% JSONObject - QUOTE method
% public static java.lang.String quote(java.lang.String string)
% Produce a string in double quotes with backslash sequences in all the right places. A backslash will be inserted within
% http://www.json.org/javadoc/org/json/JSONObject.html#quote(java.lang.String)
srcVal(1) = JSONObject.quote('C:\Program Files'); % use quote to check if a string needs to be altered to be json source text
srcVal(2) = JSONObject.quote('http://org.json');disp(srcVal) % quote returns a Java string
jo = JSONObject(['{file:',char(srcVal(1)),',url:',char(srcVal(2)),'}']);jo.toString(1) % use char to convert Java string to
%% JSONObject - GET, GET<TYPE> method
% public java.lang.Object get(java.lang.String key)
% Get the value object associated with a key.
% http://www.json.org/javadoc/org/json/JSONObject.html#get(java.lang.String)
jo = JSONObject('{module:[SunPower SPR-240-WHT-AR D,SunPower SPR-315-WHT-AR D],gen:[B50,C60]}');jo.toString(4)
modJA = jo.get('module');modJA.get(0),modJA.get(1) % matlab arrays index from 1, java arrays index from 0
genJA = jo.getJSONArray('gen'); % using getJSONArray will throw an error if value of key is not a JSONArray
%% et cetera - I think you get the idea.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.