package com.json.parse;
import net.sf.json.JSONObject;
import com.bean.Message;
public class JsonParseDemo {
public static void main(String[] args) {
String jsonString = "{\"from\":\"老周\",\"to\":\"小周\",\"content\":\"hello\",\"type\":1}";
Message msg = new Message();
JSONObject jsonObject = JSONObject.fromObject(jsonString);
msg.setFrom(jsonObject.getString("from"));
msg.setContent(jsonObject.getString("content"));
msg.setTo(jsonObject.getString("to"));
msg.setType(jsonObject.getInt("type"));
System.out.println(msg.toString());
}
}
Message.java
package com.bean;
public class Message {
private String from;
private String to;
private String content;
private int type;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Message(String from, String to, String content, int type) {
super();
this.from = from;
this.to = to;
this.content = content;
this.type = type;
}
public Message() {
super();
}
public String toString() {
return "Message [from=" + from + ", to=" + to + ", content=" + content
+ ", type=" + type + "]";
}
}
json解析所需jar包
http://download.csdn.net/detail/hoho_12/9600557
将json格式的数据存入对象中
MessageList.json
[
{
"from":"小王",
"to":"周",
"content":"好好工作!",
"type":1
},
{
"from":"周",
"to":"小王",
"content":"我会加油的,争取早日回到中南海",
"type":2
}
]
package com.json.parse;
import java.io.*;
import java.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.bean.Message;
public class MessageParse {
public static void main(String[] args) throws IOException {
String jsonString=readJson(new File("src/MessageList.json"));
//System.out.println(jsonString);
List<Message> messageList=parseJson(jsonString);
System.out.println(messageList.toString());
}
private static List<Message> parseJson(String jsonString) {
List<Message> messageList = new ArrayList<Message>();
// 将jsonString 封装成jsonArray
JSONArray jsonArray = JSONArray.fromObject(jsonString);
// jsonArray数组放的是jsonObject
for (int index = 0; index < jsonArray.size(); index++) {
JSONObject jsonObject = jsonArray.getJSONObject(index);
Message msg = new Message();
msg.setFrom(jsonObject.getString("from"));
msg.setTo(jsonObject.getString("to"));
msg.setContent(jsonObject.getString("content"));
msg.setType(jsonObject.getInt("type"));
messageList.add(msg);
}
return messageList;
}
private static String readJson(File file) throws IOException {
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
}