如何将任意JSON转换为Java中的可用结构 [英] How to convert arbitrary JSON into a usable structure in Java

查看:86
本文介绍了如何将任意JSON转换为Java中的可用结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用gson将这个返回的JSON转换为某种
数据结构,以便我可以提取有用的数据。

例如:



http ://search.twitter.com/search.json?q = test& rpp = 1

返回:

  {
completed_in:0.028,
max_id:196386333906837504,
max_id_str:196386333906837504,
next_page:?page = 2& max_id = 196386333906837504& q = test& rpp = 1,
page:1,
query:test,
refresh_url:?since_id = 196386333906837504& q = test,
results:[
{
created_at:Sat,28 Apr 2012 23:52:05 + 0000,
from_user:della_ky,
from_user_id:525641596,
from_user_id_str:525641596,
from_user_name:kydella modete,
geo:null,
id:196386333906837504,
id_str:196386333906837504,
iso_language_code:en,
metadata:{
result_type:最近
},
profile_image_url:http:\ / \ / a0.twimg.com\ / profile_images\ / 2159990525\ / webcam -toy-photo3_20_2__normal.jpg,
profile_image_url_https:https:\ / \ / si0.twimg.com\ / profile_images\ / 2159990525\ / webcam-toy-photo3_20_2__normal.jpg,
source:& lt; a href =& quot; http:\ / \ / mobile.twitter.com& quot; rel =" nofollow& quot;& gt; Mobile Web& lt; \ / a& gt;」,
text:RT @Y__U__NOOO:#SongsIKnowOffByHeart所有歌曲我听。 ,
to_user:null,
to_user_id:null,
to_user_id_str:null,
to_user_name :null
}
],
results_per_page:1,
since_id:0,
since_id_str:0
}

最终,我希望能够输出带有
名称的推文列表发送者的日期和时间。



我已经阅读了gson文档,但它已经过了我的头
说实话 - 很多新的概念对我来说。

我是否需要定义一个类,该类完全映射到
JSON的结构,然后填充该实例如果是这样的话,
看起来非常灵活/费力。理想情况下,我正在寻找一些
的东西来处理任何形式的JSON,并给我一个结构,我可以自动使用
...



是任何一个能够给我一些指针?最新消息 - 更多
的详细资料和最少音节的文字越多越好!

更新 - 感谢我已经收到的回复我已经开始组织一堂课来捕捉Twitter JSON。然而,由于JSON有一个嵌入的ArrayList对象,我正在努力一点...到目前为止,我有

  public class tweetData {
private double completed_in;
私人长期max_id;
私人长期max_id_str;
私人字符串next_page;
private int page;
私人字符串查询;
private String refresh_url;
私人列表< tweetDetails> tweets = new ArrayList< tweetDetails>();
}

  public class tweetDetails {
private String created_at;
private String from_user;
private long from_user_id;
private long from_user_id_str;
private String from_user_name;
private String geo;
私人长ID;
私人长长的id_str;
private String iso_language_code;
//metadata:
// {
//result_type:recent
//},
private String profile_image_url;
私人字符串profile_image_url_https;
私人字符串来源;
私人字符串文本;
private String to_user;
私人字符串to_user_id;
private String to_user_id_str;
private String to_user_name;
}

我正在使用实例化

  URI uri =新URI(http,search.twitter.com,/search.json,q =+ searchTerms +& rrp =+ RRP,null); 
URL twitterSearch = uri.toURL();
URLConnection yc = twitterSearch.openConnection();
JsonReader reader = new JsonReader(new InputStreamReader(yc.getInputStream()));
Gson gson = new Gson();
tweetData data = gson.fromJson(reader,tweetData.class);
System.out.println(data);

基本名称:值填充正确,但ArrayList不正确。

  tweetData:0.17196614959919140865196614959919140865?page = 2& max_id = 196614959919140865& q = test1test?since_id = 196614959919140865& q = testSIZE 0 [] 

所以,我还在挣扎 - 更多的提示非常感谢!




Tom

解决方案


我需要定义一个类它完全映射到JSON的结构,然后填充该类的一个实例?如果是这样,这似乎非常灵活/费力。


是的。 GSON 是一个库,可用于将Java对象转换为其JSON表示。它也可以用来将JSON字符串转换为等效的Java对象。这非常强大,因为您可以通过JSON表示自动实例化Java对象。假设你的JSON没有改变它的结构,你只需要定义适当的Java对象表示 一次




理想情况下,我正在寻找可以处理任何形式的JSON的东西,并给我一个我可以自动使用的结构...

然而,如果你不想自动序列化/反序列化,那么试着看一个更简单的库,比如 java.net/projects/jsonp



只需查询键就可以从中提取内容:

  final JSONObject json = new JSONObject(theJsonString); 
final String id = json.getString(max_id);
final JSONArray results = json.getJSONArray(results);
final String user = result.getJSONObject(2).getString(from_user);


I'm trying to use gson to convert this returned JSON into some kind of data structure such that I can extract useful data.

For Example:

http://search.twitter.com/search.json?q=test&rpp=1

Returns:

{
    "completed_in":0.028,
    "max_id":196386333906837504,
    "max_id_str":"196386333906837504",
    "next_page":"?page=2&max_id=196386333906837504&q=test&rpp=1",
    "page":1,
    "query":"test",
    "refresh_url":"?since_id=196386333906837504&q=test",
       "results":[
          {
             "created_at":"Sat, 28 Apr 2012 23:52:05 +0000",
             "from_user":"della_ky",
             "from_user_id":525641596,
             "from_user_id_str":"525641596",
             "from_user_name":"kydella modeste",
             "geo":null,
             "id":196386333906837504,
             "id_str":"196386333906837504",
             "iso_language_code":"en",
             "metadata":{
                "result_type":"recent"
             },
             "profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/2159990525\/webcam-toy-photo3_20_2__normal.jpg",
             "profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/2159990525\/webcam-toy-photo3_20_2__normal.jpg",
             "source":"&lt;a href=&quot;http:\/\/mobile.twitter.com&quot; rel=&quot;nofollow&quot;&gt;Mobile Web&lt;\/a&gt;",
             "text":"RT @Y__U__NOOO: #SongsIKnowOffByHeart ALL SONGS I LISTEN TO. BRAIN, Y U NO REMEMBER TEST ANSWERS LIKE THAT?!?",
             "to_user":null,
             "to_user_id":null,
             "to_user_id_str":null,
             "to_user_name":null
          }
       ],
       "results_per_page":1,
       "since_id":0,
       "since_id_str":"0"
    }

Ultimately, I would like to be able to output a list of tweets with the name of the sender and the date/time of the tweet.

I have read through the gson documentation but it's going over my head to be honest - lots of new concepts there for me.

Do I need to define a class which maps exactly to the structure of the JSON in order to then populate an instance of that class? If so this seems very inflexible/laborious. Ideally I'm looking for something which will handle JSON in any form and give me a structure I can use automatically...

Is anyone able to give me some pointers? Being new to this - the more detailed and in words of the fewest syllables the better!

Update - Thanks to the responses I've already had on this I've had a go at putting a class together to capture the twitter JSON. However, since the JSON has an embedded ArrayList of Objects I'm struggling a bit... So far I have

public class tweetData {
    private double completed_in;
    private long max_id;
    private long max_id_str;
    private String next_page;
    private int page;
    private String query;
    private String refresh_url;
    private List<tweetDetails> tweets = new ArrayList<tweetDetails>();
}

and

public class tweetDetails {
    private String created_at;
    private String from_user;
    private long from_user_id;
    private long from_user_id_str;
    private String from_user_name;
    private String geo;
    private long id;
    private long id_str;
    private String iso_language_code;
//  "metadata":
//  {
//  "result_type":"recent"
//  },
    private String profile_image_url;
    private String profile_image_url_https;
    private String source;
    private String text;
    private String to_user;
    private String to_user_id;
    private String to_user_id_str;
    private String to_user_name;
}

Which I'm instantiating with

URI uri = new URI("http", "search.twitter.com", "/search.json", "q="+ searchTerms + "&rrp=" + RRP, null);
URL twitterSearch = uri.toURL();
URLConnection yc = twitterSearch.openConnection();
JsonReader reader = new JsonReader(new InputStreamReader(yc.getInputStream()));
Gson gson = new Gson();
tweetData data = gson.fromJson(reader, tweetData.class);
System.out.println(data);

The basic name:values are being populated correctly but the ArrayList is not.

tweetData : 0.17196614959919140865196614959919140865?page=2&max_id=196614959919140865&q=test1test?since_id=196614959919140865&q=testSIZE 0[]

So, I'm still struggling a bit - any more tips hugely appreciated!

Tia, Tom

解决方案

Do I need to define a class which maps exactly to the structure of the JSON in order to then populate an instance of that class? If so this seems very inflexible/laborious.

Yes. GSON is a library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. This is really powerful because you can automagically instantiate your Java objects from the JSON representation. Assuming your JSON doesn't change its structure, you only have to define the appropriate Java object representation once.

Ideally I'm looking for something which will handle JSON in any form and give me a structure I can use automatically...

However, if you don't want automagical serialisation/deserialisation, then try looking at a simpler library such as java.net/projects/jsonp.

You can extract stuff from it just by querying the keys:

final JSONObject json = new JSONObject(theJsonString);
final String id = json.getString("max_id");
final JSONArray results = json.getJSONArray("results");
final String user = results.getJSONObject(2).getString("from_user");

这篇关于如何将任意JSON转换为Java中的可用结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆