Android简单解析Json

时间:2015-08-14 05:40:49

标签: android json

我有一个问题,我可以解析这个json:

private String strJSONValue = "{ \"Android\" :[{\"song_name\":\"Gimme Dat\",\"song_id\":\"1932\",\"artist_name\":\"Sidney Samson (Feat. Pitbull & Akon)\"},{ \"song_name\":\"F-k The Money (Remix)\",\"song_id\":\"73\",\"artist_name\":\"B.o.B. (Feat. Wiz Khalifa)\"}] }";
像这样:

String OutputData = "";
        JSONObject jsonResponse;

        try {

            /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
            jsonResponse = new JSONObject(strJSONValue);

            /***** Returns the value mapped by name if it exists and is a JSONArray. ***/
            /*******  Returns null otherwise.  *******/
            JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");

            /*********** Process each JSON Node ************/

            int lengthJsonArr = jsonMainNode.length();

            for(int i=0; i < lengthJsonArr; i++)
            {
                /****** Get Object for each JSON node.***********/
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

                /******* Fetch node values **********/
                int song_id        = Integer.parseInt(jsonChildNode.optString("song_id").toString());
                String song_name   = jsonChildNode.optString("song_name").toString();
                String artist_name = jsonChildNode.optString("artist_name").toString();


                OutputData += "Node : \n\n     "+ song_id +" | "
                        + song_name +" | "


                + artist_name +" \n\n ";
            //Log.i("JSON parse", song_name);
        }

        /************ Show Output on screen/activity **********/
        showMessage(OutputData, "STunes") ;


    } catch (JSONException e) {

        showMessage("STunes", "Error");}


            }

我的问题是如何解析这个json:

{"music":[{"external_ids":{"isrc":"GBAMC9800041","upc":"731453835122"},"play_offset_ms":117680,"external_metadata":{"deezer":{"album":{"id":1939301},"artists":[{"id":119}],"genres":[{"id":132}],"track":{"id":20309341}}},"title":"Whiskey In The Jar","duration_ms":"0","album":{"name":"Garage Inc."},"acrid":"01272c3cd88a9b38e268ed038989b885","genres":[{"name":"Pop"}],"artists":[{"name":"Metallica"}]}],"timestamp_utc":"2015-08-13 05:43:55"}

我无法找到答案

4 个答案:

答案 0 :(得分:1)

学习GSON。

http://www.jsonschema2pojo.org/

以下是课程。

-----------------------------------com.example.Album.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;

@Generated("org.jsonschema2pojo")
public class Album {

@Expose
private int id;

/**
*
* @return
* The id
*/
public int getId() {
return id;
}

/**
*
* @param id
* The id
*/
public void setId(int id) {
this.id = id;
}

}
-----------------------------------com.example.Album_.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;

@Generated("org.jsonschema2pojo")
public class Album_ {

@Expose
private String name;

/**
*
* @return
* The name
*/
public String getName() {
return name;
}

/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}

}
-----------------------------------com.example.Artist.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;

@Generated("org.jsonschema2pojo")
public class Artist {

@Expose
private int id;

/**
*
* @return
* The id
*/
public int getId() {
return id;
}

/**
*
* @param id
* The id
*/
public void setId(int id) {
this.id = id;
}

}
-----------------------------------com.example.Artist_.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;

@Generated("org.jsonschema2pojo")
public class Artist_ {

@Expose
private String name;

/**
*
* @return
* The name
*/
public String getName() {
return name;
}

/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}

}
-----------------------------------com.example.Deezer.java-----------------------------------

package com.example;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;

@Generated("org.jsonschema2pojo")
public class Deezer {

@Expose
private Album album;
@Expose
private List<Artist> artists = new ArrayList<Artist>();
@Expose
private List<Genre> genres = new ArrayList<Genre>();
@Expose
private Track track;

/**
*
* @return
* The album
*/
public Album getAlbum() {
return album;
}

/**
*
* @param album
* The album
*/
public void setAlbum(Album album) {
this.album = album;
}

/**
*
* @return
* The artists
*/
public List<Artist> getArtists() {
return artists;
}

/**
*
* @param artists
* The artists
*/
public void setArtists(List<Artist> artists) {
this.artists = artists;
}

/**
*
* @return
* The genres
*/
public List<Genre> getGenres() {
return genres;
}

/**
*
* @param genres
* The genres
*/
public void setGenres(List<Genre> genres) {
this.genres = genres;
}

/**
*
* @return
* The track
*/
public Track getTrack() {
return track;
}

/**
*
* @param track
* The track
*/
public void setTrack(Track track) {
this.track = track;
}

}
-----------------------------------com.example.Example.java-----------------------------------

package com.example;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class Example {

@Expose
private List<Music> music = new ArrayList<Music>();
@SerializedName("timestamp_utc")
@Expose
private String timestampUtc;

/**
*
* @return
* The music
*/
public List<Music> getMusic() {
return music;
}

/**
*
* @param music
* The music
*/
public void setMusic(List<Music> music) {
this.music = music;
}

/**
*
* @return
* The timestampUtc
*/
public String getTimestampUtc() {
return timestampUtc;
}

/**
*
* @param timestampUtc
* The timestamp_utc
*/
public void setTimestampUtc(String timestampUtc) {
this.timestampUtc = timestampUtc;
}

}
-----------------------------------com.example.ExternalIds.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;

@Generated("org.jsonschema2pojo")
public class ExternalIds {

@Expose
private String isrc;
@Expose
private String upc;

/**
*
* @return
* The isrc
*/
public String getIsrc() {
return isrc;
}

/**
*
* @param isrc
* The isrc
*/
public void setIsrc(String isrc) {
this.isrc = isrc;
}

/**
*
* @return
* The upc
*/
public String getUpc() {
return upc;
}

/**
*
* @param upc
* The upc
*/
public void setUpc(String upc) {
this.upc = upc;
}

}
-----------------------------------com.example.ExternalMetadata.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;

@Generated("org.jsonschema2pojo")
public class ExternalMetadata {

@Expose
private Deezer deezer;

/**
*
* @return
* The deezer
*/
public Deezer getDeezer() {
return deezer;
}

/**
*
* @param deezer
* The deezer
*/
public void setDeezer(Deezer deezer) {
this.deezer = deezer;
}

}
-----------------------------------com.example.Genre.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;

@Generated("org.jsonschema2pojo")
public class Genre {

@Expose
private int id;

/**
*
* @return
* The id
*/
public int getId() {
return id;
}

/**
*
* @param id
* The id
*/
public void setId(int id) {
this.id = id;
}

}
-----------------------------------com.example.Genre_.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;

@Generated("org.jsonschema2pojo")
public class Genre_ {

@Expose
private String name;

/**
*
* @return
* The name
*/
public String getName() {
return name;
}

/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}

}
-----------------------------------com.example.Music.java-----------------------------------

package com.example;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class Music {

@SerializedName("external_ids")
@Expose
private ExternalIds externalIds;
@SerializedName("play_offset_ms")
@Expose
private int playOffsetMs;
@SerializedName("external_metadata")
@Expose
private ExternalMetadata externalMetadata;
@Expose
private String title;
@SerializedName("duration_ms")
@Expose
private String durationMs;
@Expose
private Album_ album;
@Expose
private String acrid;
@Expose
private List<Genre_> genres = new ArrayList<Genre_>();
@Expose
private List<Artist_> artists = new ArrayList<Artist_>();

/**
*
* @return
* The externalIds
*/
public ExternalIds getExternalIds() {
return externalIds;
}

/**
*
* @param externalIds
* The external_ids
*/
public void setExternalIds(ExternalIds externalIds) {
this.externalIds = externalIds;
}

/**
*
* @return
* The playOffsetMs
*/
public int getPlayOffsetMs() {
return playOffsetMs;
}

/**
*
* @param playOffsetMs
* The play_offset_ms
*/
public void setPlayOffsetMs(int playOffsetMs) {
this.playOffsetMs = playOffsetMs;
}

/**
*
* @return
* The externalMetadata
*/
public ExternalMetadata getExternalMetadata() {
return externalMetadata;
}

/**
*
* @param externalMetadata
* The external_metadata
*/
public void setExternalMetadata(ExternalMetadata externalMetadata) {
this.externalMetadata = externalMetadata;
}

/**
*
* @return
* The title
*/
public String getTitle() {
return title;
}

/**
*
* @param title
* The title
*/
public void setTitle(String title) {
this.title = title;
}

/**
*
* @return
* The durationMs
*/
public String getDurationMs() {
return durationMs;
}

/**
*
* @param durationMs
* The duration_ms
*/
public void setDurationMs(String durationMs) {
this.durationMs = durationMs;
}

/**
*
* @return
* The album
*/
public Album_ getAlbum() {
return album;
}

/**
*
* @param album
* The album
*/
public void setAlbum(Album_ album) {
this.album = album;
}

/**
*
* @return
* The acrid
*/
public String getAcrid() {
return acrid;
}

/**
*
* @param acrid
* The acrid
*/
public void setAcrid(String acrid) {
this.acrid = acrid;
}

/**
*
* @return
* The genres
*/
public List<Genre_> getGenres() {
return genres;
}

/**
*
* @param genres
* The genres
*/
public void setGenres(List<Genre_> genres) {
this.genres = genres;
}

/**
*
* @return
* The artists
*/
public List<Artist_> getArtists() {
return artists;
}

/**
*
* @param artists
* The artists
*/
public void setArtists(List<Artist_> artists) {
this.artists = artists;
}

}
-----------------------------------com.example.Track.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;

@Generated("org.jsonschema2pojo")
public class Track {

@Expose
private int id;

/**
*
* @return
* The id
*/
public int getId() {
return id;
}

/**
*
* @param id
* The id
*/
public void setId(int id) {
this.id = id;
}

}

现在,当你需要一些东西时,你会做一些例子.getmusic.get(i).get so on

答案 1 :(得分:0)

Y2Ks答案解释: 在http://www.jsonschema2pojo.org/上,您可以生成与json匹配的类。将它们添加到您的项目中,并添加GSON库。 不,你只需要告诉GSON班级:

Gson gson = new Gson();
gson.fromJson(yourJsonString, GeneratedClass.class);

这将为您提供GeneratedClass的实例,其中包含您的数据,所有内容都包含getter和setter。

答案 2 :(得分:0)

我建议您使用Gson(来自谷歌的库)来解析json响应。这很简单,你只需要一个具有与你期望的json相同属性的类。

代码示例:

  1. 实施课程

    公共类Android {
             字符串song_name;
             int song_id;
            String artist_name;
         };

  2. 创建gson对象并初始化它。

    Gson gson = new Gson();

  3. 使用Gson将您的回复投射到Android对象中。

    对于JSONObject:

    Android android = gson.fromJson(jsonObject.toString(),Android.class);

    对于JSONArray:

    列出mAndroidList = gson.fromJson(jsonArray.toString(),new TypeToken&gt;(){}。getType());

  4. 希望它有所帮助。

答案 3 :(得分:0)

  

你需要gson-2.2.2.jar&amp;音乐的pojo

     

所以,

     

Gson gs = new Gson();

     

JSONObject jsonResponse = gs.fromJson(strJSONValue,Music.class);

     

现在使用Json-simple-1.1.1.jar

解析jsonResponse