logo
down
shadow

How to create a list from JSON objects using the GSON library?


How to create a list from JSON objects using the GSON library?

Content Index :

How to create a list from JSON objects using the GSON library?
Tag : android , By : meodudang
Date : November 24 2020, 12:01 PM

I hope this helps . Try this, below code will convert your JSON object to List using GSON library
String jsonStr = "{\"Pikachu\": {\"id\": \"266\",\"name\": \"Pikachu\"},\"Pichu\": {\"id\": \"103\",\"name\": \"Pichu\"},\"Raichu\": {\"id\": \"84\",\"name\": \"Raichu\"}}";

private List<Pokemon> getPokemonObjects() {
    try {
        List<Pokemon> pokemonList = new ArrayList<>();
        JSONObject jsonObject = new JSONObject(jsonStr);
        Iterator<String> iterator = jsonObject.keys();
        while (iterator.hasNext()){
            String key = iterator.next();
            Gson gson = new Gson();
            Pokemon pokemon = gson.fromJson(jsonObject.get(key).toString(),Pokemon.class);
            pokemonList.add(pokemon);
        }

       return pokemonList;

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to deserialize a JSON array of objects using Gson library?


Tag : java , By : abuiles
Date : March 29 2020, 07:55 AM
it helps some times To deserialize a JSONArray you need to use TypeToken. You can read more about it from GSON user guide. Example code:
@Test
public void JSON() {
    Gson gson = new Gson();
    Type listType = new TypeToken<List<MyObject>>(){}.getType();
    // In this test code i just shove the JSON here as string.
    List<Asd> asd = gson.fromJson("[{'name':\"test1\"}, {'name':\"test2\"}]", listType);
}
...
JSONArray jsonArray = ...
gson.fromJson(jsonArray.toString(), listType);
...

Is there a python json library can convert json to model objects, similar to google-gson?


Tag : python , By : JoeCh
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You could let the json module construct a dict and then use an object_hook to transform the dict into an object, something like this:
>>> import json
>>>
>>> class Person(object):
...     firstName = ""
...     lastName = ""
...
>>>
>>> def as_person(d):
...     p = Person()
...     p.__dict__.update(d)
...     return p
...
>>>
>>> s = '{ "firstName" : "John", "lastName" : "Smith" }'
>>> o = json.loads(s, object_hook=as_person)
>>>
>>> type(o)
<class '__main__.Person'>
>>>
>>> o.firstName
u'John'
>>>
>>> o.lastName
u'Smith'
>>>

Read nested json objects that have been serialized via gson library


Tag : java , By : hsdfhksh
Date : March 29 2020, 07:55 AM
To fix the issue you can do Is there a reason to use a TypeAdapter instead of mapping directly the JSON into an object? For instance with:
Gson gson = new Gson();
Info info = gson.fromJson(jsonString, Info.class)

How do i sort Nested JSON Objects using Gson Library?


Tag : android , By : alexmajy
Date : March 29 2020, 07:55 AM
should help you out The code you provided cannot even compile (broken Gson constructor invocation; Java does not provide List...). Lists cannot be cast to maps in runtime too. The JSON is broken as well, but, assuming you've provided some code, I think you wanted to parse the name located at $[(index)].terms.category[0].name:
    final String name = gson.fromJson(response, JsonElement.class).getAsJsonArray()
            .get(index).getAsJsonObject()
            .get("terms").getAsJsonObject()
            .get("category").getAsJsonArray()
            .get(0).getAsJsonObject()
            .get("name").getAsJsonPrimitive()
            .getAsString();
    System.out.println(name);

How to form the json using the gson library to having loop thorugh the objects, lists?


Tag : java , By : Ed.
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I'd suggest you create a constructor for each class that takes all the required values. That way you can create the objects with much less code.
MainClass.java:
  import java.util.ArrayList;
  import java.util.List;
  import com.google.gson.Gson;
  import com.xxx.nsp.constants.Values;
  import com.xxx.nsp.dto.Address;
  import com.xxx.nsp.dto.SendCVConfirmationNotification;
  import com.xxx.nsp.dto.VisibilityInfo;
  import com.xxx.nsp.dto.VisibilityType;
  import com.xxx.nsp.json.NSPNotificationRequest;
  public class MainClass {
      public static void main(String[] args) {  

          Address addr = new Address(Values.addressType, Values.addressLine1, 
            Values.addressLine2, Values.addressLine3, Values.politicalDivision,
            Values.city, Values.state, Values.zipcode, null, Values.phoneNumber);

          List<String> accountNumbers = new ArrayList<>();
          accountNumbers.add("1233");
          accountNumbers.add("2234");

          List<VisibilityInfo> visibilityInfo = new ArrayList<>();        
          visibilityInfo.add(new VisibilityInfo(VisibilityType.THIRD_PARTY,
            accountNumbers, addr));  

          SendCVConfirmationNotification scv = new SendCVConfirmationNotification(
            Values.enroleeName, Values.companyName, Values.nickName, visibilityInfo, 
            Values.hasClaims, Values.hasReturns, Values.cvURL, null); 

          NSPNotificationRequest nr = new NSPNotificationRequest(Values.transactionId,
            Values.clientId, Values.destinationAddress, scv, Values.locale,
            Values.mediaType, Values.pageId);

          Gson gsonObj = new Gson();
          String jsonStr = gsonObj.toJson(nr);
          System.out.println(jsonStr);
      }
  } 
public SendCVConfirmationNotification(String enroleeName, String companyName,
  String nickName, List<VisibilityInfo> visibilityInfo, boolean hasClaims,
  boolean hasReturns, String cvURL, String emailId){
    this.enroleeName = enroleeName;
    this.companyName = companyName;
    this.nickName = nickName;
    this.visibilityInfo = visibilityInfo;
    this.hasClaims = hasClaims;
    this.hasReturns = hasReturns;
    this.cvURL = cvURL;
    this.emailId = emailId;
}
public VisibilityInfo(VisibilityType visibilityType, List<String> accountNumbers,
  Address receivingAddress){
    this.visibilityType = visibilityType;
    this.accountNumbers = accountNumbers;
    this.receivingAddress = receivingAddress;
}
public Address(AddressType addressType, String addressLine1, String addressLine2,
  String addressLine3, String politicalDivision, String city, String state, String zipcode,
  String country, String phoneNumber){
    this.addressType = addressType;
    this.addressLine1 = addressLine1;
    this.addressLine2 = addressLine2;
    this.addressLine3 = addressLine3;
    this.politicalDivision = politicalDivision;
    this.city = city;
    this.state = state;
    this.zipcode = zipcode;
    this.country = country;
    this.phoneNumber = phoneNumber;
}
public NSPNotificationRequest(String transactionId, String clientId,
  String destinationAddress, SendCVConfirmationNotification sendCVConfirmationNotification,
  String locale, String mediaType, String pageId){
    this.transactionId = transactionId;
    this.clientId = clientId;
    this.destinationAddress = destinationAddress;
    this.sendCVConfirmationNotification = sendCVConfirmationNotification;
    this.locale = locale;
    this.mediaType = mediaType;
    this.pageId = pageId;
    //if this class includes any other properties, include them accordingly
}
public enum VisibilityType {
    INBOUND,
    OUTBOUND,
    FOURTH_PARTY,
    THIRD_PARTY;
}
 public static void main(String[] args) {  

      List<VisibilityInfo> visibilityInfo = new ArrayList<>(); 

      List<String> accountNumbers = new ArrayList<>();
      accountNumbers.add("1233");
      accountNumbers.add("6722");       
      visibilityInfo.add(new VisibilityInfo(VisibilityType.FOURTH_PARTY,
        accountNumbers, null));

      List<String> accountNumbers = new ArrayList<>();
      accountNumbers.add("6152");
      accountNumbers.add("1277");       
      visibilityInfo.add(new VisibilityInfo(VisibilityType.OUTBOUND,
        accountNumbers, null));

      Address addr = new Address(Values.addressType, null, 
        null, null, null, "downtown test", "NY", "7539", "US", null);    
      visibilityInfo.add(new VisibilityInfo(VisibilityType.OUTBOUND,
        null, addr));

      SendCVConfirmationNotification scv = new SendCVConfirmationNotification(
        Values.enroleeName, Values.companyName, Values.nickName, visibilityInfo, 
        Values.hasClaims, Values.hasReturns, Values.cvURL, null); 

      NSPNotificationRequest nr = new NSPNotificationRequest(Values.transactionId,
        Values.clientId, Values.destinationAddress, scv, Values.locale,
        Values.mediaType, Values.pageId);

      Gson gsonObj = new Gson();
      String jsonStr = gsonObj.toJson(nr);
      System.out.println(jsonStr);
  }
Related Posts Related QUESTIONS :
  • Fragment is reloaded each time after rejecting location permission
  • How to read ViewModel data from sttrings.xml list of items
  • Flutter doctor does not see vs code ,VS code does not detect flutter/bin
  • How to build aar in flutter
  • Is displayMetrix xdpi and ydpi accurate?
  • How to detect doubletap on a View?
  • how to play an encrypted file in Android
  • Android: keytool error on the command line when locating debug.keystore
  • Android paint/canvas issue; drawing smooth curves
  • Problems with starting an activity in onStart
  • Performance of map overlay in conjunction with ItemizedOverlay is very poor
  • How to change android indeterminate ProgressBar color?
  • How do I change the Mobile Country Code (MCC) in the Android Emulator?
  • Stop Progressbar manual scrolling in Android
  • Android: download large file
  • Android : uploaded .apk file to server but cant download that .apk file
  • How do I distribute Android app to beta tester without using Market
  • Android Unable to launch the Inbox from a notification
  • Android: Ringer mode changed to silent doesn't stop the phone vibrating
  • Change the side the text appears on a radio button
  • Check the memory usage anp cpu and power of an application in android
  • What is the String 'volumeName' argument of MediaStore.Audio.Playlists.Members.getContentUri referring to?
  • Playing Multiple sounds at the same time in Android
  • Android: how to change the time in emulator?
  • close the soft key pad when i click on other views in android
  • Setting the position within a spinner
  • How to play ringtone/alarm sound in Android
  • How to adjust text font size to fit textview
  • "Android 2.x" vs "Google APIs" for Android AVD Setup
  • How to center buttons on screen horizontally and vertically plus equidistant apart?
  • Discrete seekbar in Android app?
  • Gradle Build Fails - Illegal exception table range in class file com/google/wireless/android/sdk/stats/GradleBuildMemory
  • register has type Long (High Half) but expected Long (Low Half)
  • Is it good idea to use Dispatcher.Main with delay( )?
  • WebView and Advanced View is Not loading partiucalr URL
  • How to show three dots at the end of text view
  • Is it possible to run macros within Android Studio project?
  • Adding a button with default appearance but changed background color
  • What is best way to show notification at a certain time in Android?
  • Jetifier not working when library uses android component and app uses androidx component
  • How can I write the contents of an image in a filesystem
  • Retrieve a list of images from the Database and display them using a ListView?
  • java.lang.SecurityException: my location requires permission ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
  • Timer/hourglass wont stop
  • How can I make AndroidX the default library for new Android projects?
  • Is it okay to delete buildToolsVersion android studio because of a warning in the Asyncstorage library?
  • Can I call a class that doesn't have an activity withIntent?
  • Android TextView fontFamily not working when set via TextAppearance
  • Unable to find nearby places
  • Is there any way to launch my application right away without 'Ok Google"?
  • Places api set location biased based on current location
  • Layout Preview is not displaying layout when Material Design is added
  • How do I resolve this diamond problem in Kotlin?
  • How to update the custom value in a view model object
  • How to stop refreshing/re-creating activity when updating Firebase data using setValue?
  • Manifest Permissions vs App Setttings Permissions
  • NumberFormatException in Try-Catch while converting String to Int
  • How to pass observable fields through include tag?
  • Next button on Android keyboard not submitting form
  • Does Firestore support automatic functions for updates?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com