プログラム言語 JSONデータ操作
概要
JavaScriptObjectNotesion
JavaScriptのオブジェクトを操作できる表記法を用いたデータ形式
表記法
(1) { キー : 値 , キー : 値 }
(2) キー、値、ともに「"」で囲む
{ "name": "John Smith", "age": 33 }
配列
[ "要素1", "要素2", "要素3" ]
読み込み
System.Runtime.Serialization
[DataContract]
public class FriendInfo
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Address { get; set; }
[DataMember]
public int Age { get; set; }
}
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
private void Form1_Load(object sender, EventArgs e)
{
//(1)読み込むJSONデータ
var jsonString = @"{
""Address"" : ""Nishinomiya"",
""Age"" : 35,
""Name"" : ""Yone""
}";
//(2)DataContractJsonSerializerをインスタンス化
var serializer = new DataContractJsonSerializer(type: typeof(FriendInfo));
//(3)JSONデータを文字列からバイト配列に変換
var jsonBytes = Encoding.Unicode.GetBytes(jsonString);
//(4)バイト配列を読み込むMemoryStreamクラスを定義
var sr = new MemoryStream(jsonBytes);
//(5)ReadObjectメソッドでJSONデータを.NETオブジェクトに変換
var obj = (FriendInfo)serializer.ReadObject(sr);
⇒
obj.Name : Yone
obj.Age : 35
obj.Address : Nishinomiya
}
String s = "{\"return\":\"OK\",\"errorcode\":\"E90000\"}";
Map<String, String> map = new LinkedHashMap<String, String>();
ObjectMapper mapper = new ObjectMapper();
map = mapper.readValue(s, new TypeReference<LinkedHashMap<String, String>>(){});
for (Map.Entry<String, String> entity : map.entrySet()){
String key = entity.getKey();
key : return、errorcode
String value = entity.getValue();
value : OK、E90000
}
System.out.println(map);
→{return=OK, errorcode=E90000}
MAP→JSON
s = mapper.writeValueAsString(map);
System.out.println(s);
→{"return":"OK","errorcode":"E90000"}
"id": "12345",
"name": "米 良太",
"email": "yone@office-yone.com"
}
連想配列→JSONに変換
let json = JSON.stringify(user);
JSON→連想配列に変換
let json = JSON.parse(json);
JSONキーをオブジェクトとして扱える
console.log(json.id);
→124345
書き込み
obj.Address = "kobe";
var ms = new MemoryStream();
serializer.WriteObject(stream: ms, graph: obj);
jsonString = Encoding.UTF8.GetString(ms.ToArray());
jsonString : {“Address”:”kobe“,”Age”:32,”Name”:”Doi”}