logo
down
shadow

How to write a method to read JSON files of different structures and return different POJO objects in Java?


How to write a method to read JSON files of different structures and return different POJO objects in Java?

By : user2956898
Date : November 22 2020, 03:03 PM
hope this fix your issue I have multiple JSON files of different structures, to read through my program. For example, , use interfaces
code :
public interface JSONable{
     String toString();
     //other common methods
}

public Pojo1 implements JSONable{
     public String toString(){
       super.toString();
    }
}


Share : facebook icon twitter icon
Recursive method to return different objects stored as JSON files

Recursive method to return different objects stored as JSON files


By : AdamV
Date : March 29 2020, 07:55 AM
Does that help Ok, so you have two files, one with list of devices and the other, per-device file, which has attributes of the device. The structures of the two files is exactly same, I am guessing something like
The devices file:
code :
{{"DeviceName:"d1","UserName":"u1","Password":"p1","DeviceType":"t1","IPAddress":"i1"},
 {"DeviceName:"d2","UserName":"u2","Password":"p2","DeviceType":"t2","IPAddress":"ir"}}
{{"tagName:"n1","tagType":"t1","tagXPath":"X1","tagWritable":true}}
java jackson: get from url rest web service call pojo's (with inner pojo's) as json and map them back to pojo

java jackson: get from url rest web service call pojo's (with inner pojo's) as json and map them back to pojo


By : srinivas
Date : March 29 2020, 07:55 AM
Hope that helps SOLUTION thanks to @peeskillet:
MyPojo myPojo = mapper.readValue(connection.getInputStream(), MyPojo.class);
Read JSON Request and Map to JAVA POJO

Read JSON Request and Map to JAVA POJO


By : PasinduKOH
Date : March 29 2020, 07:55 AM
I wish did fix the issue. With GSON
code :
public class Data {
    @SerializedName("customerData") @Expose private List<CustomerData> customerData = null;
}

public class CustomerData {
    @SerializedName("primaryData") @Expose private List<PrimaryData> primaryData = null;
    @SerializedName("officeData") @Expose private OfficeData officeData;
    @SerializedName("ContactData") @Expose private ContactData contactData;
}

public class PrimaryData {
    @SerializedName("HNo") @Expose private String hNo;
    @SerializedName("APTNM") @Expose private String aPTNM;
    @SerializedName("STRT") @Expose private String sTRT;
}

public class OfficeData {
    @SerializedName("ADDR") @Expose private String aDDR;
    @SerializedName("STRT") @Expose private String sTRT;
    @SerializedName("LM") @Expose private String lM;
}

public class ContactData {
    @SerializedName("PHNO") @Expose private String pHNO;
    @SerializedName("ZIP") @Expose private String zIP;
    @SerializedName("MAILCD") @Expose private String mAILCD;
}


Gson gson = new Gson();
Data data = gson.fromJson(dataJSON, Data.class);
Read/write POJO in Database as JSON string

Read/write POJO in Database as JSON string


By : Bardo Salgado
Date : March 29 2020, 07:55 AM
should help you out You could define a converter to convert between the Pojo and JSON and use Jackson to make the conversion:
code :
@Converter
public class MyPojoToJsonConverter implements AttributeConverter<MyPojo, String>{

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(MyPojo myPojo) {
        String json = "";
        try {
            json = objectMapper.writeValueAsString(myPojo);
        } catch (JsonProcessingException jpe) {
            // Handle exception
        }
        return json;
    }

    @Override
    public MyPojo convertToEntityAttribute(String myPojoAsJson) {
        MyPojo myPojo = null;
        try {
            myPojo = objectMapper.readValue(myPojoAsJson, MyPojo.class);
        } catch (JsonParseException e) {
            // HandleException
        } catch (JsonMappingException e) {
            // HandleException
        } catch (IOException e) {
            // HandleException
        }
        return myPojo;
    }
}
@Entity
@Table(name = "mytable")
public class MyEntity {

    @Id
    private String key;

    @Convert(converter=MyPojoToJsonConverter.class)
    private MyPojo content;
}
Parse JSON to list of POJO objects using POJO object class

Parse JSON to list of POJO objects using POJO object class


By : user2004648
Date : March 29 2020, 07:55 AM
seems to work fine I am forced to use an interface method with the signature which I can not change: , Solved it, finally:
code :
@Override
List parse(String path, Class clazz) {
    List result = []
    JsonArray jsonArray = new JsonParser()
            .parse(new File(path).getText(CHARSET))
            .getAsJsonArray()

    Gson gson = new Gson()
    jsonArray.each {
        result.add(gson.fromJson(it, clazz))
    }
    return result
}
Related Posts Related Posts :
  • The type org.openqa.selenium.firefox.FirefoxDriver is not accessible
  • Limitations (drawbacks) of java programming language?
  • Error: ')' expected Error: illegal start of expression
  • TableRowSorter use LookAndFeel of TableHeader, but own Comparator
  • Difference between @GeneratedValue and @GenericGenerator
  • Design Scenario: Smartphone class and will have derived classes like IPhone,AndroidPhone,WindowsMobilePhone can be even
  • Java date parsing without separators?
  • how to map an array of custom type from postgres to java using hibernate
  • Why hibernate always call "update" statement after using "select" statement in MySQL?
  • An interview topic: What can go wrong with this code?
  • How do I regex remove whitespace and newlines from a text, except for when they are in a json's string?
  • How to turn off Preferences > Compiles > User External Build?
  • how to convert arraylist to string array with all items in double quote
  • PMD+Maven+JAVA Error:: Can't find resource rulesets/comments.xml. Make sure the resource is a valid file or URL or is on
  • How to extend AbstractScheduledService.Scheduler
  • Primefaces tabview: set Active Index after some counting
  • Need help in Regex to exclude splitting string within "
  • Get header from HttpUrlConnection object
  • encoding xlsx as base64 and send it as an attachment
  • How to acess HttpServletRequest in Jaas login module in Tomcat
  • How to implement a basic pointer
  • Java Swing Exit Icon?
  • Why onNext has no effect
  • IntelliJ Idea 2018.2 no option for importing gradle project
  • Remove a negative element from an array w/o array.copy
  • Could this prevent overflow in Java?
  • In Java Swing, can I receive Caret events in real time?
  • I need help not using brute force when using JFrames and DrawWindows
  • How do I refactor ArrayList<MyClass> into MyClassLIst?
  • My program keeps saying that the method cannot be resolved
  • BubbleSort -my code returns random addresses
  • JavaFX components inside HTML?
  • Character in Java game not responding
  • Working around access denied in a FileWalking Tree in Java7
  • How to avoid if/else when using multple suppliers?
  • How to pass object from table cell editor to Table Model?
  • Paypal Sandbox payment state pending
  • sejda-console.bat passing parameters with spaces
  • Multiple Consumers Spring Kafka
  • Bitbucket pipeline: environmental variables in build.gradle file not recognized
  • Java static enum method to return a default enum value
  • What is the complexity of empty for loop?
  • Group randomly List of Lists as N subsets with K elements in each
  • How to set texture on a shape drawn by glDrawArrays()?
  • How to make a jlabel resizable according to the window
  • Java Mathematical Expression Syntax
  • assigning values to characters in java
  • Method overriding and Inheritance in java
  • given a set of lists/groups with a series of number, find matching numbers
  • Connection to HID USB device (keyboard and mouse) in android
  • Inject HttpServletRequest in CDI SessionScoped bean
  • Pool game in java - ball collision algorithm
  • Focus ScrollView to selected position programmatically - Android
  • Is it hibernate bug?
  • Glib memory allocation error
  • Android Proguard - step by step
  • Setting the pivot point of a JPanel to its center
  • java check time is greater time
  • how to save a screenshot (matlab)
  • Anti-aliasing filled shapes in libgdx
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org