将JSON解析为java对象
您好,我有以下任务: 包含JSON对象的URL:将JSON解析为java对象,java,json,Java,Json,您好,我有以下任务: 包含JSON对象的URL: - Write a program to read/write URL - Parse data in URL using JSON to JAVA Object - display 3 variables to user from the object - Find entity/list of object =
- Write a program to read/write URL
- Parse data in URL using JSON to JAVA Object
- display 3 variables to user from the object
- Find entity/list of object = Find object that has ‘name’
- Find Object that has ‘author’
- Find Object that has ‘item’
*通过注释定义如何将JSON定义到Java列表中,并找到包含“name”的对象
我认为问题是在不使用任何java库的情况下解析JSON。到目前为止,我已经开发了以下代码:
class JSONObject {
HashMap map = new HashMap();
}
public class SYW {
public static String sampleUrl = "https://api.github.com/users/mralexgray/repos";
public static Integer index = 1;
public static void main(String[] args) {
//String sampleJSON = fetchJSON(sampleUrl);
JSONObject json = getJSONObject("{\"login\": \"mralexgray\",\"id\": 262517,\"avatar_url\": \"https://avatars.githubusercontent.com/u/262517?v=3\"}");
// suppose there is a owner class
populateJavaObject(json, Owner.class);
}
public static void populateJavaObject(JSONObject json, Class class1) {
// TODO Auto-generated method stub
Object obj = null;
try {
obj = class1.newInstance();
Iterator it = json.map.keySet().iterator();
while (it.hasNext()) {
String key = (String)it.next();
Object value = json.map.get(key);
Field field = class1.getDeclaredField(key);
field.setAccessible(true);
if (value instanceof Integer) {
field.setInt(obj, (Integer)value);
} else if (value instanceof String) {
field.setString(obj, (String)value);
}
}
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getString(String jsonStr) {
int i = index;
StringBuffer buf = new StringBuffer();
while (jsonStr.charAt(i) != '\"') {
jsonStr.charAt(i);
buf.append(jsonStr.charAt(i));
i++;
}
index = i;
return buf.toString();
}
public static JSONObject getJSONObject (String jsonStr) {
StringBuffer buf = new StringBuffer();
boolean isKey = true;
String currentKey = "";
Object currentValue = "";
JSONObject json = new JSONObject();
while (jsonStr.charAt(index) != '}') {
if (jsonStr.charAt(index) == '\"') {
index++;
String token = getString(jsonStr);
if (isKey) {
currentKey = token;
} else {
currentValue = token;
}
} else if (Character.isDigit(jsonStr.charAt(index))) {
Integer token = getNumber(jsonStr);
currentValue = token;
} else if (jsonStr.charAt(index) == '{') {
currentValue = getJSONObject(jsonStr);
} else if (jsonStr.charAt(index) == '[') {
currentValue = getArray(jsonStr);
} else if (jsonStr.charAt(index) == ':') {
isKey = false;
} else if (jsonStr.charAt(index) == ',' || jsonStr.charAt(index) == '}') {
isKey = true;
json.map.put(currentKey, currentValue);
}
index++;
}
return json;
}
private static ArrayList getArray(String jsonStr) {
ArrayList list = new ArrayList();
while (jsonStr.charAt(index) != ']') {
index++;
}
return null;
}
private static Integer getNumber(String jsonStr) {
// TODO Auto-generated method stub
Integer num = 0;
while (Character.isDigit(jsonStr.charAt(index))) {
num = num * 10 + Integer.parseInt(jsonStr.charAt(index)+"");
index++;
}
index--;
return num;
}
public static Object parseJSON(String jsonStr) {
Owner owner = new Owner();
while (index <= jsonStr.length()) {
if (jsonStr.charAt(index) == '{') {
return getJSONObject(jsonStr);
} else if (jsonStr.charAt(index) == '[') {
return getArray(jsonStr);
}
}
return null;
}
public static String fetchJSON(String url) {
String nextLine = "";
try {
URL sywURL = new URL(url);
BufferedReader reader = new BufferedReader(new InputStreamReader(sywURL.openStream()));
StringBuffer buf = new StringBuffer();
while ((nextLine = reader.readLine()) != null) {
buf.append(nextLine);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return nextLine;
}
}
类JSONObject{
HashMap=newHashMap();
}
公共类SYW{
公共静态字符串sampleUrl=”https://api.github.com/users/mralexgray/repos";
公共静态整数索引=1;
公共静态void main(字符串[]args){
//字符串sampleJSON=fetchJSON(sampleUrl);
JSONObject json=getJSONObject(“{\”登录\“:\”mralexgray\”,\“id\”:262517,\”化身url\“:\”https://avatars.githubusercontent.com/u/262517?v=3\"}");
//假设有一个owner类
populateJavaObject(json,Owner.class);
}
公共静态void populateJavaObject(JSONObject json,类class1){
//TODO自动生成的方法存根
objectobj=null;
试一试{
obj=class1.newInstance();
Iterator it=json.map.keySet().Iterator();
while(it.hasNext()){
String key=(String)it.next();
Object value=json.map.get(key);
字段字段=class1.getDeclaredField(键);
字段。setAccessible(true);
if(值instanceof Integer){
字段.setInt(obj,(整数)值);
}else if(字符串的值实例){
字段设置字符串(obj,(字符串)值);
}
}
}捕获(实例化异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(非法访问例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(无此字段例外){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(安全异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
公共静态字符串getString(字符串jsonStr){
int i=指数;
StringBuffer buf=新的StringBuffer();
while(jsonStr.charAt(i)!=“\”){
查拉特(一);
buf.append(jsonStr.charAt(i));
i++;
}
指数=i;
返回buf.toString();
}
公共静态JSONObject getJSONObject(字符串jsonStr){
StringBuffer buf=新的StringBuffer();
布尔值isKey=true;
字符串currentKey=“”;
对象currentValue=“”;
JSONObject json=新的JSONObject();
while(jsonStr.charAt(index)!='}'){
如果(jsonStr.charAt(索引)='\'){
索引++;
字符串标记=getString(jsonStr);
如果(isKey){
currentKey=token;
}否则{
currentValue=令牌;
}
}else if(Character.isDigit(jsonStr.charAt(index))){
整数令牌=getNumber(jsonStr);
currentValue=令牌;
}else if(jsonStr.charAt(index)='{'){
currentValue=getJSONObject(jsonStr);
}else if(jsonStr.charAt(index)='['){
currentValue=getArray(jsonStr);
}else if(jsonStr.charAt(index)=':'){
isKey=false;
}else if(jsonStr.charAt(index)=','| | jsonStr.charAt(index)='}'){
isKey=true;
json.map.put(currentKey,currentValue);
}
索引++;
}
返回json;
}
私有静态ArrayList getArray(字符串jsonStr){
ArrayList=新建ArrayList();
而(jsonStr.charAt(index)!=']''){
索引++;
}
返回null;
}
私有静态整数getNumber(字符串jsonStr){
//TODO自动生成的方法存根
整数num=0;
while(Character.isDigit(jsonStr.charAt(index))){
num=num*10+整数.parseInt(jsonStr.charAt(index)+“”);
索引++;
}
索引--;
返回num;
}
公共静态对象parseJSON(字符串jsonStr){
所有者=新所有者();
虽然(index“我认为问题是在不使用任何java库的情况下解析JSON”,但我个人认为这是完全相反的
软件工程原则1是“不要重新发明轮子”
我认为“通过注释定义如何将JSON定义到Java列表中,并找到其中包含“name”的对象”。这是一个强烈的提示,可以将注释与Jackson解析器一起使用——这将是解决此问题的标准方法。可能OP出于教育原因想要构建一个解析器,这是他被要求创建的一个有效原因读一个URL和“解析数据”,而不是“写一个PARSER”。这是一个面试问题,一个公司需要你自己编写代码,而不是使用一个图书馆/框架。如果他们是那种“我”的公司,我会找别的地方工作。如果他们把图书馆当成“欺骗”,你不想知道。他是一个核心java职位。因此,他们会要求你发明不同的新算法和数据结构。他们提出此类问题,以了解你在核心java中的思维过程和优势。大多数公司,如微软、亚马逊等,都会进行此类采访。