logo
down
shadow

Parsing and Mapping a JSON Object with Dynamic Properties


Parsing and Mapping a JSON Object with Dynamic Properties

Content Index :

Parsing and Mapping a JSON Object with Dynamic Properties
Tag : java , By : tlync
Date : November 29 2020, 03:01 PM

I wish did fix the issue. My solution was a tiered one.
First, the discovery that Moxy just doesn't do maps was frightening, but rather reliving once I found that the be the issue. So I had to change my default serializer from Moxy to Jackson. This was done easily by changing the pom.xml:
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>${jersey.version}</version>
</dependency>

Comments
No Comments Right Now !

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

Share : facebook icon twitter icon

Parsing JSON without Object Mapping in Restkit iOS


Tag : objective-c , By : Ike
Date : March 29 2020, 07:55 AM
like below fixes the issue You can simply call parsedBody:nil on your RKResponse object and assign the returned object to an NSDictionary:
responseDict = [response parsedBody:nil];
- (bool) wasRequestSuccessfulWithResponse:(RKResponse*)response {

    bool isSuccessfulResponse = NO; 

    id parsedResponse;

    NSDictionary *responseDict;

    if(response != nil) {

        parsedResponse = [response parsedBody:nil];

        if ([parsedResponse isKindOfClass:[NSDictionary class]]) {

            responseDict = [response parsedBody:nil];

            if([[responseDict objectForKey:@"success"] boolValue]) {

                isSuccessfulResponse = YES;
            }
        }

    } 

    return isSuccessfulResponse;

}

Parsing JSON with dynamic properties


Tag : chash , By : user184975
Date : March 29 2020, 07:55 AM
Hope that helps It looks like the issue is in the NameserversOnIPAddressResult class definition. Its ip_dns property should be directly of type Dictionary. (This is for the same reason that the items property of CheckedServer is correctly a Dictionary type.)
Although I haven't manually verified this, I believe the affected code should look like:
public class NameserversOnIPAddressResult
{
    public Dictionary<string, CheckedServer> ip_dns { get; set; }
}

Parsing JSON Object with variable properties into strongly typed object


Tag : chash , By : Puneet Madaan
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further If you must have strongly typed result I would deserialize Profile as a dictionary of superposition of properties
class AbscdeClass
{
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
    public string D { get; set; }
    public string E { get; set; }
}

class JsonBody
{
    public Dictionary<string, AbscdeClass> Profile { get; set; }
}
JsonBody json = JsonConvert.DeserializeObject<JsonBody>(jsonString);

Light weight jar to achieve both JSON parsing & object mapping


Tag : java , By : AnthonyC
Date : March 29 2020, 07:55 AM
will be helpful for those in need I checked gson & found both Parsing & Object Mapping are achiveved using it.
Parsing :
JsonArray jArray = new JsonParser().parse(json1).getAsJsonArray();

for (int j = 0; j < jArray.size(); j++) {
    JsonObject jObject = jArray.get(j).getAsJsonObject();
    String url = jObject.getAsJsonObject("details").get("url").getAsString();
 }
JsonObject jObject = new JsonParser().parse(json2).getAsJsonObject();
Gson gson = new Gson();
UserDetail userDetail = gson.fromJson(jObject.toString(), UserDetail.class);

Handling unknown Json properties when mapping Json object to POJO


Tag : java , By : Cowtung
Date : March 29 2020, 07:55 AM
it fixes the issue This requires a special post-processing type adapter that can do both deserialization and collecting unknown properties. I would do it similar to the following.
The following interface is a sort of a bridge between a real object and the type adapter. Nothing special here.
interface IUnknownPropertiesConsumer {

    void acceptUnknownProperties(JsonObject jsonObject);

}
final class MyClass
        implements IUnknownPropertiesConsumer {

    final String sub = null;
    final String iss = null;
    transient JsonObject customProperties;

    @Override
    public void acceptUnknownProperties(final JsonObject customProperties) {
        this.customProperties = customProperties;
    }

}
final class UnknownPropertiesTypeAdapterFactory
        implements TypeAdapterFactory {

    private static final TypeAdapterFactory instance = new UnknownPropertiesTypeAdapterFactory();

    private UnknownPropertiesTypeAdapterFactory() {
    }

    static TypeAdapterFactory get() {
        return instance;
    }

    @Override
    public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
        // Check if we can deal with the given type
        if ( !IUnknownPropertiesConsumer.class.isAssignableFrom(typeToken.getRawType()) ) {
            return null;
        }
        // If we can, we should get the backing class to fetch its fields from
        @SuppressWarnings("unchecked")
        final Class<IUnknownPropertiesConsumer> rawType = (Class<IUnknownPropertiesConsumer>) typeToken.getRawType();
        @SuppressWarnings("unchecked")
        final TypeAdapter<IUnknownPropertiesConsumer> delegateTypeAdapter = (TypeAdapter<IUnknownPropertiesConsumer>) gson.getDelegateAdapter(this, typeToken);
        // Excluder is necessary to check if the field can be processed
        // Basically it's not required, but it makes the check more complete 
        final Excluder excluder = gson.excluder();
        // This is crucial to map fields and JSON object properties since Gson supports name remapping
        final FieldNamingStrategy fieldNamingStrategy = gson.fieldNamingStrategy();
        final TypeAdapter<IUnknownPropertiesConsumer> unknownPropertiesTypeAdapter = UnknownPropertiesTypeAdapter.create(rawType, delegateTypeAdapter, excluder, fieldNamingStrategy);
        @SuppressWarnings("unchecked")
        final TypeAdapter<T> castTypeAdapter = (TypeAdapter<T>) unknownPropertiesTypeAdapter;
        return castTypeAdapter;
    }

    private static final class UnknownPropertiesTypeAdapter<T extends IUnknownPropertiesConsumer>
            extends TypeAdapter<T> {

        private final TypeAdapter<T> typeAdapter;
        private final Collection<String> propertyNames;

        private UnknownPropertiesTypeAdapter(final TypeAdapter<T> typeAdapter, final Collection<String> propertyNames) {
            this.typeAdapter = typeAdapter;
            this.propertyNames = propertyNames;
        }

        private static <T extends IUnknownPropertiesConsumer> TypeAdapter<T> create(final Class<? super T> clazz, final TypeAdapter<T> typeAdapter,
                final Excluder excluder, final FieldNamingStrategy fieldNamingStrategy) {
            final Collection<String> propertyNames = getPropertyNames(clazz, excluder, fieldNamingStrategy);
            return new UnknownPropertiesTypeAdapter<>(typeAdapter, propertyNames);
        }

        @Override
        public void write(final JsonWriter out, final T value)
                throws IOException {
            typeAdapter.write(out, value);
        }

        @Override
        public T read(final JsonReader in) {
            // JsonParser holds no state so instantiation is a bit excessive, but Gson may change in the future
            final JsonParser jsonParser = new JsonParser();
            // In its simplest solution, we can just collect a JSON tree because its much easier to process
            final JsonObject jsonObjectToParse = jsonParser.parse(in).getAsJsonObject();
            final JsonObject unknownProperties = new JsonObject();
            for ( final Map.Entry<String, JsonElement> e : jsonObjectToParse.entrySet() ) {
                final String propertyName = e.getKey();
                // No in the object fields?
                if ( !propertyNames.contains(propertyName) ) {
                    // Then we assume the property is unknown
                    unknownProperties.add(propertyName, e.getValue());
                }
            }
            // First convert the above JSON tree to an object
            final T object = typeAdapter.fromJsonTree(jsonObjectToParse);
            // And do the post-processing
            object.acceptUnknownProperties(unknownProperties);
            return object;
        }

        private static Collection<String> getPropertyNames(final Class<?> clazz, final Excluder excluder, final FieldNamingStrategy fieldNamingStrategy) {
            final Collection<String> propertyNames = new ArrayList<>();
            // Class fields are declared per class so we have to traverse the whole hierarachy
            for ( Class<?> i = clazz; i.getSuperclass() != null && i != Object.class; i = i.getSuperclass() ) {
                for ( final Field declaredField : i.getDeclaredFields() ) {
                    // If the class field is not excluded
                    if ( !excluder.excludeField(declaredField, false) ) {
                        // We can translate the field name to its property name counter-part
                        final String propertyName = fieldNamingStrategy.translateName(declaredField);
                        propertyNames.add(propertyName);
                    }
                }
            }
            return propertyNames;
        }

    }

}
private static final Gson gson = new GsonBuilder()
        .registerTypeAdapterFactory(UnknownPropertiesTypeAdapterFactory.get())
        .create();

...

// Assuming jsonReader is a reader to read your original JSON
final MyClass o = gson.fromJson(jsonReader, MyClass.class);
System.out.println(o.sub);
System.out.println(o.iss);
System.out.println(o.customProperties);
value
value2
{"unknown_property":"value3","unknown_property_2":{"a":1,"b":2}}
Related Posts Related QUESTIONS :
  • Android Studio onClick not working in BindViewHolder
  • How to use Spring Converter for some controllers only?
  • How verify that 3 numbers in sequence are equals?
  • When using .compareTo to compare dates, why doesn't it take Months into account?
  • Does the perfomance of "filter then map" and "map then filter" differ in a Stream?
  • How can I set the initial Delay after pressing the start Button to a specific time (HH:mm:ss) format
  • How to switch between Android devices during the tests
  • How to configure java.util.logging via properties to use standard output?
  • How to iterate through array in order
  • Is there better way of iteration to find the evenly divisible number?
  • How do I avoid using if statements with a large amount of variables in java
  • Writing JUnit test cases for a Spring Boot Service Application with autowired components
  • Cors for GET with Postman not showing headers
  • Printing values in different column same row using APACHE POI
  • Fully decompile java6 web application
  • Passing keycloak configuration parameters in the code rather than reading from application.properties
  • setDataSource() IO exception
  • Unexpected Output while retrieving Data from mongodb and displaying in a csv file?
  • Algorithm for searching a value in two arrays
  • How to avoid casting with generic return values?
  • Java/RegEx - Negation of pattern not working
  • How to split a string to non empty words if it might include a separator like tab on first place
  • Supplier<Sequence<String>> cannot be iterated more than once
  • Why there is only one thread can actually started in @PostConstruct method?
  • Manage CompletionStage inside of Netty handler
  • Url Problem while Developing on Localhost and deploy on Remote Virtual Server
  • How to identify the missing type id in Jackson error?
  • android data binding error: cannot find symbol
  • Spring Boot application with a jar dependency does not run after maven build
  • Spring Data JPA query , filter ? search engine ? JPQL?
  • Why LiveData returns null in ViewModel?
  • what this line of code mean....new URLClassLoader(new URL[0],getClass().getClassLoader());
  • Why do need to use new Random() instead of just Random Randomnum?
  • I want to access zk components from the java file
  • How do I cast FieldValue.serverTimestamp() to Kotlin/Java Date Class
  • Insertion Sort Double Array with User Input - JAVA
  • Creating 2 dimesional array with user input and find sum of specific columns
  • can not get Advertising ID Provider in android
  • Convert list of Objects to map of properties
  • How to represent an undirected weighted graph in java
  • Return values as array from collection
  • ByteBuddy generic method return cast to concrete type
  • ImageView hides the round corners of the parent
  • Is there a way to find setter method by its getter method or vice versa in a class?
  • Get aggregated list of properties from list of Objects(Java 8)
  • Unable to find a document in Mongodb where exact date match in java
  • UsernamePasswordAuthenticationFilter skips success handler
  • Use Java filter on stream with in a stream filter
  • Default Login not successful in spring boot 2.1.7
  • Adding key value pairs from a file to a Hashmap
  • Rub regex: matching a char except when after by another char
  • Convert Base64 String to String Array
  • Escape Unicode Character 'POPCORN' to HTML Entity
  • An empty JSON field which is a boolean/nullable field in Java model, is getting converted as null
  • Mongo java driver cannot find public constructor for interface
  • How to unit test writing a file to AWS Lambda output stream?
  • How to make a GitHub GraphQL API Call from Java
  • What's the difference between @ComponentScan and @Bean in a context configuration?
  • Expected class or package adding a view using a class
  • can be delete of a element in a static array be O(1)?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com