How to print the json to listview included two data? - java

I want to display two data on listview through the json input. All the code are alter from internet which I got error. I have not clear logic to understand the meaning of the code. Please give me advice and alter my code.
private void displayArrayList(String jsonStr){
String[] from = {"eventName", "date"};
int[] to = {R.id.eventName, R.id.date};
SimpleAdapter simpleAdapter = new SimpleAdapter (
getActivity(),convertToWordArrayList(jsonStr), R.layout.listview_layout,from,to);
simpleAdapter.notifyDataSetChanged();
listView.setAdapter(simpleAdapter);
}
private ArrayList<HashMap<String, ActivityInfo>> convertToWordArrayList(String jsonStr){
JSONObject jsonObject ;
ArrayList<HashMap<String, ActivityInfo>> arrayList = new ArrayList<HashMap<String, ActivityInfo>>();
try{
jsonObject = new JSONObject(jsonStr);
JSONArray jsonArray=jsonObject.getJSONArray("article");
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObjRow=jsonArray.getJSONObject(i);
ActivityInfo activityInfo =new ActivityInfo();
activityInfo.eventName = jsonObjRow.getString("eventName");
activityInfo.date = jsonObjRow.getString("date");
HashMap<String, String> map= new HashMap<String, ActivityInfo>();
map.put("eventName", activityInfo.eventName );
map.put("date", activityInfo.date);
JSONArray jsonArray2=jsonObjRow.getJSONArray("content");
for (int j=0;j<jsonArray2.length();j++) {
JSONObject jsonObjRow2 = jsonArray2.getJSONObject(j);
activityInfo.review = jsonObjRow2.getString("review");
}
arrayList.add(activityInfo);
}
}catch (JSONException e){
e.printStackTrace();
}
return arrayList;
}
ActivityInfo class (using the serializable to got the result )
public class ActivityInfo implements Serializable {
String eventName;
String date ;
public void setEventName(String eventName){
this.eventName =eventName ;
}
public String toString(){
return this.eventName;
}
}
Json Response is no problem
{
"article":[
{
"activityId":"5c5d8addd404c",
"eventName":"running",
"date":"2019-02-08",
"content":[
{
"review":"you there"
},
{
"review":"please go away"
},
]
},
{
"activityId":"5c5d8b318df62",
"eventName":"basketball",
"date":"2019-02-13",
"content":[
{
"review":"confirm again"
}
]
},
{
"activityId":"5c5d8b9308018",
"eventName":"playing",
"date":"2019-02-16",
"content":[
{
"review":"provid of you"
}
]
}
]
}

I totally do it like this:
public class menuCreation()
{
public string Category { get; set; }
public string ItemName { get; set; }
public string Price { get; set; }
public string FileName { get; set; }
public menuCreation[] Arr { get; set; }
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string json = (reader.ReadToEnd());
List<menuCreation> items = JsonConvert.DeserializeObject<List<menuCreation>>(json);
Arr = items.ToArray();
}
menuCreation mc = new menuCreation();
foreach (var item in mc.Arr)
{
PictureBox pb = new PictureBox();
pb.Tag = item.ItemName;
pb.Name = item.Price;
}
You can see, I reach itemName with class object.So, you can add listview with this method.

This is your Model Class..
ActivityInfo.java
public class ActivityInfo implements Serializable {
String eventName;
String date;
public void setEventName(String eventName){
this.eventName = eventName ;
}
public String getEventName(){
return this.eventName;
}
public void setDate(String date){
this.date = date;
}
public String getDate(){
return date;
}
}
This will be your final errorfree code..
private void displayArrayList(String jsonStr){
String[] from = {"eventName", "date"};
int[] to = {R.id.eventName, R.id.date};
SimpleAdapter simpleAdapter = new SimpleAdapter (
getActivity(),convertToWordArrayList(jsonStr), R.layout.listview_layout,from,to);
simpleAdapter.notifyDataSetChanged();
listView.setAdapter(simpleAdapter);
}
private ArrayList<HashMap<String,String>> convertToWordArrayList(String jsonStr){
JSONObject jsonObject;
ArrayList<HashMap<String,String>> arrayList = new ArrayList();
try{
jsonObject = new JSONObject(jsonStr);
JSONArray jsonArray=jsonObject.getJSONArray("article");
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObjRow=jsonArray.getJSONObject(i);
HashMap<String,String> hashMap=new HashMap<>();//create a hashmap to store the data in key value pair
hashMap.put("eventName",jsonObjRow.getString("eventName"));
hashMap.put("date",jsonObjRow.getString("date"));
JSONArray jsonArray2=jsonObjRow.getJSONArray("content");
/*If you want to get Content Reviews from Json, you need to make another attributes like Content in ActivityInfo Class*/
arrayList.add(hashmap);
}
}catch (JSONException e){
e.printStackTrace();
}
return arrayList;
}

Related

sort jsonarray of data in descending order

[
{
"id":"1",
"created_at":"2019-08-19 02:54:36",
"updated_at":"2019-09-04 15:00:05"
},
{
"id":"2",
"created_at":"2019-08-27 08:59:18",
"updated_at":"2019-09-04 14:59:14"
},
{
"id":"4",
"created_at":"2019-08-29 20:19:54",
"updated_at":"2019-09-04 14:58:53"
}
]
how do i sort json data according to "created_at" (2019-08-30,2019-08-29) data in descending order and set value to textview in android.
please try this
public static JSONArray sortJsonArray(JSONArray array) {
List<JSONObject> jsons = new ArrayList<JSONObject>();
for (int i = 0; i < array.length(); i++) {
jsons.add(array.getJSONObject(i));
}
Collections.sort(jsons, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject lhs, JSONObject rhs) {
String lid = lhs.getString("created_at");
String rid = rhs.getString("created_at");
// Here you could parse string id to integer and then compare.
return lid.compareTo(rid);
}
});
return new JSONArray(jsons);
}
A solution using gson library:
public static void setSortedDate (String json, TextView tv) {
Type t = new TypeToken<List<DateModel>>(){}.getType();
Gson gson = new Gson();
List<DateModel> list = gson.fromJson(json, t);
Collections.sort(list, new Comparator<DateModel>(){
#Override
public int compare (DateModel p1, DateModel p2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date d1 = df.parse(p1.created_at);
Date d2 = df.parse(p2.created_at);
return d2.compareTo(d1);
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
});
int i = list.size();
for(DateModel d: list){
tv.append(d.created_at);
if(--i > 0) tv.append(", ");
}
}
Model class
public class DateModel {
String id;
String created_at;
String updated_at;
}
Usage
private static final String JSON = "[ { \"id\": \"1\", \"created_at\": \"2019-08-19 02:54:36\", \"updated_at\": \"2019-09-04 15:00:05\" }, { \"id\": \"2\", \"created_at\": \"2019-08-27 08:59:18\", \"updated_at\": \"2019-09-04 14:59:14\" }, { \"id\": \"4\", \"created_at\": \"2019-08-29 20:19:54\", \"updated_at\": \"2019-09-04 14:58:53\" }, { \"id\": \"5\", \"created_at\": \"2019-08-30 09:31:42\", \"updated_at\": \"2019-09-04 14:58:40\" } ]";
setSortedDate(JSON, tv);
Output
2019-08-30 09:31:42, 2019-08-29 20:19:54, 2019-08-27 08:59:18, 2019-08-19 02:54:36
Update
Here is the replacement of gson with standard java implementation
public static void setSortedDate (String json, TextView tv) {
List<DateModel> list = getListFromJson(json);
Collections.sort(list, new DateModelComparator());
int i = list.size();
for(DateModel d: list){
tv.append(d.created_at);
if(--i > 0) tv.append(", ");
}
}
private static List<DateModel> getListFromJson (String json) {
List<DateModel> list = new LinkedList<>();
try {
JSONArray array = new JSONArray(json);
for(int i=0;i<array.length();i++){
JSONObject obj = array.getJSONObject(i);
DateModel dm = new DateModel();
dm.id = obj.getString("id");
dm.created_at = obj.getString("created_at");
dm.updated_at = obj.getString("updated_at");
list.add(dm);
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
DateComparator class
public class DateModelComparator implements Comparator<DateModel> {
#Override
public int compare (DateModel p1, DateModel p2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date d1 = df.parse(p1.created_at);
Date d2 = df.parse(p2.created_at);
return d2.compareTo(d1);
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
}

How to parsing JSON from presenter and set to RecyclerView(Android)

I try to get xml data then I parse it to JSON, I use OkHttp as a connection. I managed to get data from LOG but I can't display it in my RecyclerView, when I LOG to adapter and the result is size 0
I set the response to the model and sharedpreference
The point of the problem is that I just don't understand how to take the response from the presenter then I set it to the adapter in the main Fragment.
public class ParentCategories {
#SerializedName("idkategori")
#Expose
private String idkategori;
#SerializedName("namakategori")
#Expose
private String namakategori;
#SerializedName("fileicon")
#Expose
private String fileicon;
#SerializedName("subkategori")
#Expose
private SubCategories subkategori;
public ParentCategories(Parcel in) {
this.idkategori = in.readString();
this.namakategori = in.readString();
this.fileicon = in.readString();
}
public ParentCategories() {
}
public String getIdkategori() {
return idkategori;
}
public void setIdkategori(String idkategori) {
this.idkategori = idkategori;
}
public String getNamakategori() {
return namakategori;
}
public void setNamakategori(String namakategori) {
this.namakategori = namakategori;
}
public String getFileicon() {
return fileicon;
}
public void setFileicon(String fileicon) {
this.fileicon = fileicon;
}
public SubCategories getSubkategori() {
return subkategori;
}
public void setSubkategori(SubCategories subkategori) {
this.subkategori = subkategori;
}
}
public class CategoriesPresenter {
....
public void onResponse(Call call, Response response) throws IOException {
String mMessage = response.body().string();
JSONObject jsonObj = null;
try {
jsonObj = XML.toJSONObject(mMessage);
JSONObject jsonObject = new JSONObject(jsonObj.toString());
JSONObject object = jsonObject.getJSONObject("posh");
String attr2 = object.getString("resultcode");
com.davestpay.apphdi.helper.Log.d("hasil", String.valueOf(object));
if (attr2.equalsIgnoreCase("0000")) {
String idAgen = object.getString("idagen");
int jumlahKategori = object.getInt("jumlahkategori");
JSONArray category = object.getJSONArray("kategori");
List<ParentCategories> parentCategories = new ArrayList<ParentCategories>();
for (int i = 0; i < category.length(); i++) {
ParentCategories categories = new ParentCategories();
JSONObject c = category.getJSONObject(i);
Log.d(TAG, "onResponseC: "+c);
String idKategori = c.getString("idkategori");
String namaKategori = c.getString("namakategori");
Log.d(TAG, "onResponseNamaKategori: "+namaKategori);
String fileIcon = c.getString("fileicon");
JSONObject subCategories = c.getJSONObject("subkategori");
JSONArray subCategory = subCategories.getJSONArray("kategori2");
Log.d(TAG, "onResponseSubCategories: "+subCategory);
for (int subCatPosition = 0; subCatPosition < subCategory.length(); subCatPosition++) {
SecondCategories secondCategories = new SecondCategories();
List<SecondCategories> listSecondCategories = new ArrayList<>();
JSONObject sc = subCategory.getJSONObject(subCatPosition);
String secIdKategori = sc.getString("idkategori");
String secNamaKategori = sc.getString("namakategori");
String secFileIcon = sc.getString("fileicon");
secondCategories.setIdkategori(secIdKategori);
secondCategories.setNamakategori(secNamaKategori);
secondCategories.setFileicon(secFileIcon);
listSecondCategories.add(secondCategories);
}
categories.setIdkategori(idKategori);
categories.setNamakategori(namaKategori);
categories.setFileicon(fileIcon);
parentCategories.add(categories);
Log.d(TAG, "onResponseFinalCategories: "+parentCategories);
}
iCategories.onSuccessCategories(parentCategories);
preferenceHelper.clear(PreferenceHelper.CATEGORIES);
preferenceHelper.putList(PreferenceHelper.CATEGORIES, parentCategories);
} else {
Log.d(TAG, "onResponse: ");
}
} catch (JSONException e) {
com.davestpay.apphdi.helper.Log.e("JSON exception", e.getMessage());
e.printStackTrace();
}
}
}
private void getInit() {
if (preferenceHelper != null) {
idAgen = preferenceHelper.getString(PreferenceHelper.ID_AGEN);
namaAgen = preferenceHelper.getString(PreferenceHelper.NAMA_AGEN);
password = preferenceHelper.getString(PreferenceHelper.PASSWORD);
categories = preferenceHelper.getList(PreferenceHelper.CATEGORIES, ParentCategories[].class);
}
authPresenter = new AuthPresenter(getContext());
presenter = new CategoriesPresenter();
presenter.setBaseView(this);
presenter.onCreate(getContext());
if (authPresenter.isLoggedIn()) {
// kategori.setText(categories.toString());
presenter.getCategories(idAgen, password, counter);
}
kategori = mView.findViewById(R.id.kategori);
categories = new ArrayList<>();
rvMain = mView.findViewById(R.id.rv_categories);
adapter = new CategoriesListViewAdapter(getContext(), categories);
layoutManager = new LinearLayoutManager(getdActivity());
adapter.notifyDataSetChanged();
rvMain.setLayoutManager(layoutManager);
rvMain.setAdapter(adapter);
}
This is the problem.
categories = new ArrayList<>();
Here, you are initialising categories to new ArrayList<>(); It is like you are creating a new arraylist.
Just remove this line.

Split jsonarray data into multiple list using array value

I want to split an ArrayList according to the existing data, Like as
category etc.
I try nested for loop and add them into list.but It's not working.
String url = "http://27.147.169.230/UpSkillService/UpSkillsService.svc/" + "GetCNCCourseDefByorg/" + 1 +"/" +1;
Ion.with(getApplicationContext())
.load("GET",url)
.setBodyParameter("","")
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
Log.d("Result",result);
try {
JSONObject obj =new JSONObject(result);
JSONArray jsonArray = obj.getJSONArray("GetCNCCourseDefByorgResult");
//Arrays.sort(new JSONArray[]{jsonArray});
if(obj.isNull("GetCNCCourseDefByorgResult"))
{
Toast.makeText(getApplicationContext(),"No Course Found",Toast.LENGTH_SHORT).show();
}
else if (!obj.equals(null)) {
String cata="";
Log.d("Resul3", jsonArray.toString());
for (int i = 0; i < jsonArray.length(); i++) {
final CourseCatagory catagoryModel = new CourseCatagory();
JSONObject course = jsonArray.getJSONObject(i);
CourseList courselist = new CourseList();
if(cata!=course.getString("CategoryName"))
{
Log.d("Catagory",cata);
catagoryModel.setCategoryName(course.getString("CategoryName"));
arrayListcatagory.add(catagoryModel);
for (int j=0;j<jsonArray.length();j++)
{
JSONObject cat1 = jsonArray.getJSONObject(j);
cata=cat1.getString("CategoryName");
Log.d("cat",cata);
if(cat1.getString("CategoryName")==course.getString("CategoryName"))
{
courselist.setCourseName(cat1.getString("CourseName"));
courselist.setCourseCode(cat1.getString("CourseCode"));
courselist.setWishFlag(cat1.getInt("WishFlag"));
Log.d("Course",cat1.getString("CourseName"));
arrayListcourse.add(courselist);
}
else {
}
}
}
catagoryModel.setCourseList(arrayListcourse);
}
adapter.notifyDataSetChanged();
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
});
}
`
I want as catagory, under catagory course shown which match catagory name.
Accounting>Introduction Accounting,Advance accounting
Finance>Introduction Finance
You can Use HashMap<String,ArrayList<CategoryDetails>> to resolve your Problem.
First Create CategoryDetails POJO class
class CategoryDetails {
private courseName;
private courseCode;
private wishFlag;
//make setter and getter methods for above fields.
}
Then use category Name as key in HashMap to differentiate as mentioned in first line of my answer.
Map<String,ArrayList<CategoryDetails>> listCategory = new HashMap<String,ArrayList<CategoryDetails>>;

Volley post method JSONArray

anyone can suggest me how to POST volley JSONArray body like
{
"mobileNo":"9876543210",
"dobDocuments" : [
"http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/dob_proofs/DOB Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/dob_proofs/DOB Proof2.jpg"
],
"educationDocuments" : [
"http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/edu_proofs/EDU Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/edu_proofs/EDU Proof2.jpg"
],
"addressDocuments" : [
"http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/add_proofs/ADD Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/add_proofs/ADD Proof2.jpg"
]
}
for this instance I've Hashmap which contains this array data.
I searched lot but not getting proper solution for this type.
Thank you..!
Try this
JSONObject sendObject = new JSONObject();
try {
JSONArray dobDocuments = new JSONArray();
dobDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
dobDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
JSONArray educationDocuments = new JSONArray();
educationDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
educationDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
JSONArray addressDocuments = new JSONArray();
addressDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
addressDocuments.put("https://stackoverflow.com/questions/50128021/volley-post-method-jsonarray");
sendObject.put("dobDocuments", dobDocuments);
sendObject.put("educationDocuments", addressDocuments);
sendObject.put("addressDocuments", addressDocuments);
sendObject.put("mobileNo", "9876543210");
} catch (JSONException e) {
}
Log.e("JSONObject",sendObject.toString());
OUTPUT
{
"dobDocuments": ["https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray", "https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray"],
"educationDocuments": ["https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray", "https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray"],
"addressDocuments": ["https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray", "https:\/\/stackoverflow.com\/questions\/50128021\/volley-post-method-jsonarray"],
"mobileNo": "9876543210"
}
If you want to use model classes and comfortable with GSON.
Add this to build.gradle
implementation 'com.google.code.gson:gson:2.8.4'
Create class for your request/response
class MyRequest {
private String mobileNo;
private String[] dobDocuments;
private String[] educationDocuments;
private String[] addressDocuments;
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public String[] getDobDocuments() {
return dobDocuments;
}
public void setDobDocuments(String[] dobDocuments) {
this.dobDocuments = dobDocuments;
}
public String[] getEducationDocuments() {
return educationDocuments;
}
public void setEducationDocuments(String[] educationDocuments) {
this.educationDocuments = educationDocuments;
}
public String[] getAddressDocuments() {
return addressDocuments;
}
public void setAddressDocuments(String[] addressDocuments) {
this.addressDocuments = addressDocuments;
}
}
Now create JSONObject
try {
MyRequest myRequest = new MyRequest();
myRequest.setMobileNo("9876543210");
myRequest.setDobDocuments(new String[] {"http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/dob_proofs/DOB Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/dob_proofs/DOB Proof2.jpg"});
myRequest.setEducationDocuments(new String[]{ "http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/edu_proofs/EDU Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/edu_proofs/EDU Proof2.jpg"});
myRequest.setAddressDocuments(new String[]{"http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/add_proofs/ADD Proof1.jpg","http://server.com/test/uploads/users/5ae699bb8ec8d8218f18c3b4/5ae699f58ec8d8218f18c3b5/add_proofs/ADD Proof2.jpg"});
JSONObject jsonObject = new JSONObject(new Gson().toJson(myRequest));
Log.e("jsonObject", jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}

Json parsing with nested array using Gson

I have not seen an (answered) example on the web which discusses this kind of nested-json-array.
JSON to be parsed:
{
"Field": {
"ObjectsList": [
{
"type": "Num",
"priority": "Low",
"size": 3.43
},
{
"type": "Str",
"priority": "Med",
"size": 2.61
}
]
}
}
I created a class for each 'level' of nested json block. I want to be able to parse the contents of the "ObjectList" array.
Can anyone help me to parse this JSON using Gson in Java?
Any hints or code-snippets would be greatly appreciated.
My approach is the following:
public static void main (String... args) throws Exception
{
URL jsonUrl = new URL("http://jsonUrl.com") // cannot share the url
try (InputStream input = jsonUrl.openStream();
BufferedReader buffReader = new BufferedReader (new InputStreamReader (input, "UTF-8")))
{
Gson gson = new GsonBuilder().create();
ClassA classA = gson.fromJson(buffReader, ClassA.class);
System.out.println(classA);
}
}
}
class ClassA
{
private String field;
// getter & setter //
}
class ClassB
{
private List<ClassC> objList;
// getter & setter //
}
clas ClassC
{
private String type;
private String priority;
private double size;
// getters & setters //
public String printStr()
{
return String.format(type, priority, size);
}
}
The following snippet and source file would help you:
https://github.com/matpalm/common-crawl-quick-hacks/blob/master/links_in_metadata/src/com/matpalm/MetaDataToTldLinks.java#L17
private static ParseResult NO_LINKS = new ParseResult(new HashSet<String>(), 0);
private JsonParser parser;
public static void main(String[] s) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(s[0]));
MetaDataToTldLinks metaDataToTldLinks = new MetaDataToTldLinks();
while (reader.ready()) {
String[] fields = reader.readLine().split("\t");
ParseResult outboundLinks = metaDataToTldLinks.outboundLinks(fields[1]);
System.out.println(tldOf(fields[0]) + " " + outboundLinks.links);
}
}
public MetaDataToTldLinks() {
this.parser = new JsonParser();
}
public ParseResult outboundLinks(String jsonMetaData) {
JsonObject metaData = parser.parse(jsonMetaData.toString()).getAsJsonObject();
if (!"SUCCESS".equals(metaData.get("disposition").getAsString()))
return NO_LINKS;
JsonElement content = metaData.get("content");
if (content == null)
return NO_LINKS;
JsonArray links = content.getAsJsonObject().getAsJsonArray("links");
if (links == null)
return NO_LINKS;
Set<String> outboundLinks = new HashSet<String>();
int numNull = 0;
for (JsonElement linke : links) {
JsonObject link = linke.getAsJsonObject();
if ("a".equals(link.get("type").getAsString())) { // anchor
String tld = tldOf(link.get("href").getAsString());
if (tld == null)
++numNull;
else
outboundLinks.add(tld);
}
}
return new ParseResult(outboundLinks, numNull);
}
public static String tldOf(String url) {
try {
String tld = new URI(url).getHost();
if (tld==null)
return null;
if (tld.startsWith("www."))
tld = tld.substring(4);
tld = tld.trim();
return tld.length()==0 ? null : tld;
}
catch (URISyntaxException e) {
return null;
}
}
public static class ParseResult {
public final Set<String> links;
public final int numNull;
public ParseResult(Set<String> links, int numNull) {
this.links = links;
this.numNull = numNull;
}
}
How about this snippet?:
if (json.isJsonArray()) {
JsonArray array = json.getAsJsonArray();
List<Object> out = Lists.newArrayListWithCapacity(array.size());
for (JsonElement item : array) {
out.add(toRawTypes(item));
}
}

Categories