简体   繁体   English

如何将任意JSON转换为Java中的可用结构

[英]How to convert arbitrary JSON into a usable structure in Java

I'm trying to use gson to convert this returned JSON into some kind of data structure such that I can extract useful data. 我正在尝试使用gson将此返回的JSON转换为某种数据结构,以便我可以提取有用的数据。

For Example: 例如:

http://search.twitter.com/search.json?q=test&rpp=1 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":"<a href="http:\/\/mobile.twitter.com" rel="nofollow">Mobile Web<\/a>",
             "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. 我已经阅读了gson文档,但说实话 - 我有很多新概念。

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? 我是否需要定义一个完全映射到JSON结构的类,然后填充该类的实例? 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... 理想情况下,我正在寻找能够以任何形式处理JSON的东西,并给我一个我可以自动使用的结构......

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. 更新 - 感谢我已经对此做出的回应,我已经开始将一个类放在一起来捕获twitter JSON。 However, since the JSON has an embedded ArrayList of Objects I'm struggling a bit... So far I have 但是,由于JSON有一个嵌入的对象ArrayList,我有点挣扎......到目前为止,我有

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. 基本名称:正确填充值但ArrayList不正确填充。

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? 我是否需要定义一个完全映射到JSON结构的类,然后填充该类的实例? If so this seems very inflexible/laborious. 如果是这样,这似乎非常不灵活/费力。

Yes. 是。 GSON is a library that can be used to convert Java Objects into their JSON representation. GSON是一个可用于将Java对象转换为其JSON表示的库。 It can also be used to convert a JSON string to an equivalent Java object. 它还可用于将JSON字符串转换为等效的Java对象。 This is really powerful because you can automagically instantiate your Java objects from the JSON representation. 这非常强大,因为您可以从JSON表示自动实例化Java对象。 Assuming your JSON doesn't change its structure, you only have to define the appropriate Java object representation once . 假设您的JSON没有更改其结构,您只需要定义一次适当的Java对象表示。

Ideally I'm looking for something which will handle JSON in any form and give me a structure I can use automatically... 理想情况下,我正在寻找能够以任何形式处理JSON的东西,并给我一个我可以自动使用的结构......

However, if you don't want automagical serialisation/deserialisation, then try looking at a simpler library such as java.net/projects/jsonp . 但是,如果您不想进行自动序列化/反序列化,那么请尝试查看更简单的库,例如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");

Gson actually does all the serialization for you. Gson实际上为您完成了所有序列化。 So yes, you would have to write the classes yourself. 所以是的,你必须自己编写课程。 To you, this seams inflexible and laborious, but that's only because that library isn't made for what you're asking for (it doesn't parse 'arbitrary' JSON). 对你而言,这种接缝是不灵活和费力的,但这只是因为该库不是为你所要求的而制作的(它不解析'任意'JSON)。

I would suggest at least considering writing the classes and using gson. 我建议至少考虑编写类并使用gson。 The reason I say that is because either way your application's logic will have to expect a very specific format, and writing out that format in a Java class will make things tidier. 我之所以这么说是因为你的应用程序的逻辑必须要求一种非常特定的格式,并且在Java类中写出这种格式会使事情变得更加整洁。 Here's a nice guide that will help you get started that way. 这是一个很好的指南 ,可以帮助您以这种方式开始。

If you want to simply decode the JSON without serializing it into a Java class (IMHO the only way to use 'arbitrary' JSON), you'll want to use another library. 如果你想简单地解码JSON而不将其序列化为Java类(恕我直言,使用'任意'JSON的唯一方法),你将需要使用另一个库。 Try this one. 试试这个吧 It allows you to decode the JSON, and use it by getting values from it (as described in this question: Convert a JSON string to object in Java ME? ). 它允许您解码JSON,并通过从中获取值来使用它(如本问题中所述: 在Java ME中将JSON字符串转换为对象? )。

There are some tools that do gson to schema mapping. 有一些工具可以将gson用于模式映射。 You give some sample JSON responses, and the java classes to access them are created for you. 您提供了一些示例JSON响应,并为您创建了访问它们的java类。

http://www.jsonschema2pojo.org/ http://www.jsonschema2pojo.org/

Gson is a slick beast! Gson是一个光滑的野兽! Or at least it became so over the years that have passed since the question had been asked. 或者至少自问题问题以来已经过去了多年。

You can pass it an Object.class as a second parameter to the fromJson() method and it will parse your Json into a reasonable structure of LinkedTreeMap s and ArrayList s. 您可以将Object.class作为第二个参数传递给fromJson()方法,它会将您的Json解析为LinkedTreeMapArrayList的合理结构。

Object result = (new Gson()).fromJson(jsonString, Object.class)

More than that, you can really do partial parsing and leave loose ends at any level of your object structure by defining a certain field as Object! 更重要的是,通过将某个字段定义为Object,您可以真正进行部分解析并在对象结构的任何级别留下松散的末端!

Gson will then parse Json into your structure and your field of type Object will contain the above mentioned structure of LinkedTreeMap s and ArrayList s. 然后Gson将Json解析为您的结构,Object类型的字段将包含LinkedTreeMapArrayList的上述结构。

Eg, you may define a class 例如,您可以定义一个类

Person {
    String name;
    Object details;
}

(Imagine, you care mostly about the person's name but may want the details also somewhere. To log them, for instance.) (想象一下,你主要关心的是这个人的名字,但也可能想要某些地方的细节。例如,要记录它们。)

Then you can pass the following Json to the fromJson(input, Person.class) method as a first parameter 然后,您可以将以下Json作为第一个参数传递给fromJson(input,Person.class)方法

{ 
    "name": "Carlsson", 
    "details": {
        "address": "Stockholm",
        "phones": [
            "work": "233-322-233-322",
            "home": "none"
        ]
    }
}

The result will have the name field filled with "Carlsson" string and details field will contain a LinkedTreeMap with keys "address" and "phones" , etc. 结果将使用“Carlsson”字符串填充名称字段, 详细信息字段将包含带有“地址”“电话”等键的LinkedTreeMap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM