Mostrar anuncios nativos en Android

Nota:

La metodología de recuento de impresiones nativas sigue la metodología de recuento en procesamiento que se utiliza para las creatividades de banners: una impresión se activará tan pronto como se procese el anuncio nativo, independientemente de su tiempo en la pantalla. Esto garantizará una mayor precisión y una mejor capacidad de entrega, mejorando así el rendimiento general.

Los anuncios nativos te dan la posibilidad de crear anuncios personalizados para que coincidan con el aspecto del resto de tu aplicación. Esta página describe nuestra API de anuncios nativos a un nivel general e incluye un ejemplo de uso.

Redes nativas admitidas a través de la mediación:

  • Facebook
  • AdMob y DFP

Para ofrecer anuncios nativos, enviarás una solicitud de anuncio nativo y recibirás una respuesta de anuncio nativo. Para Android 9 y versiones posteriores y API v. 28 y versiones posteriores, la solicitud debe ser HTTPS de forma predeterminada para realizar un seguimiento preciso de la visibilidad. Puede habilitar HTTPS con useHttps(true).

En el código de ejemplo siguiente:

  • Configure un objeto de solicitud y proporciónelo:

    • El identificador de ubicación (como se muestra en el código de ejemplo siguiente), O

    • Una combinación de código de inventario e identificación de miembro:

      public NativeAdRequest nativeAdRequest= new NativeAdRequest(context, "PLACEMENT_ID");
      //public NativeAdRequest nativeAdRequest= new NativeAdRequest(context, "INVENTORY_CODE", MEMBER_ID);
      
  • Opcionalmente, puede establecer el renderer_id para este NativeAdRequest. (Para obtener más información, renderer_id consulte Servicio de diseño nativo). Las renderer_id necesidades deben especificarse para que vastxml, me gusta, descargas, precio de venta, teléfono, dirección y URL para mostrar se devuelvan en el NativeAdResponsearchivo .

    nativeAdRequest.setRendererId(RENDERER_ID);
    
  • Registre un agente de escucha que señale los eventos de anuncios nativos, como los clics (NativeAdEventListener).

  • Registre un agente de escucha para señalar el estado de la solicitud nativa: correcto o incorrecto. El agente de escucha debe implementar la NativeAdRequestListener interfaz.

  • Si la solicitud tiene éxito (es decir, NativeAdListener.onAdLoaded() se activa), los activos de anuncios nativos se cargan en el NativeAdResponse objeto, que se pueden usar en vistas que coincidan con el aspecto nativo de la aplicación. A continuación, registre la vista principal o de contenedor de estas vistas para habilitar el seguimiento de impresiones y clics.

  • Anule el registro de la vista de anuncios nativos después de haber completado el flujo de trabajo. Cuando se llama al método de anulación de registro, el script de visibilidad OMID del SDK de Xandr Mobile genera un informe masivo de la sesión OMID durante el flujo de trabajo. Por lo tanto, es importante que los editores implementen esta API que facilita una medición precisa de la visibilidad.

Nota:

Mantener referencias a vistas nativas y objetos de respuesta nativos. Mantener referencias a vistas nativas y objetos de respuesta nativos.

Es su responsabilidad mantener una referencia a la vista y NativeAdResponse el objeto de anuncios nativos si es necesario.

public class MyActivity extends Activity {
 
    Context activityContext;
    NativeAdResponse nativeAdResponse;
    LinearLayout container;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        activityContext = this;
 
        // Create a NativeAdRequest object
        NativeAdRequest adRequest = new NativeAdRequest(activityContext, "123456"); // Placement ID
         
        // Optionally set the renderer_id
        //adRequest.setRendererId(123);
 
        // Create a listener for ad events
        NativeAdEventListener adEventListener = new
                NativeAdEventListener() {
                    @Override
                    public void onAdWasClicked() {
                        // Do something when the view is clicked
                    }
 
                    @Override
                    public void onAdWillLeaveApplication() {
                        // Do something when the ad is taking user away from current app
                    }
 
                    @Override
                    public void onAdWasClicked(String clickUrl, String fallbackURL) {
                        // Handle Click URL
                    }
                };
 
        // Whether to pre-load the native ad's icon and main image
        adRequest.shouldLoadIcon(true);
        adRequest.shouldLoadImage(true);
 
        adRequest.setListener(new NativeAdRequestListener() {
            @Override
            public void onAdLoaded(NativeAdResponse response) {
                nativeAdResponse = response;
                // Cover image
                ImageView imageView = new ImageView(activityContext);
                imageView.setImageBitmap(response.getImage());
 
                // Icon image
                ImageView iconView = new ImageView(activityContext);
                iconView.setImageBitmap(response.getIcon());
 
                // Title
                TextView title = new TextView(activityContext);
                title.setText(response.getTitle());
 
                // Main text
                TextView description = new TextView(activityContext);
                description.setText(response.getDescription());
 
                // Text that indicates a call to action -- for example, to install an app
                TextView callToAction = new TextView(activityContext);
                callToAction.setText(response.getCallToAction());
 
                // Create a container (a parent view that holds all the
                // views for native ads)
                LinearLayout container = new LinearLayout(activityContext);
                container.addView(iconView);
                container.addView(title);
 
                // Add the native ad container to the view hierarchy
                LinearLayout ad_frame = findViewById(R.id.native_ad_frame);
                ad_frame.addView(container);
            }
 
            @Override
            public void onAdFailed(ResultCode errorcode) {
 
            }
        });
 
        // Call loadAd() to request a response once
        adRequest.loadAd();
 
        // Register native views for click and impression tracking.  The
        // adEventListener is the listener created above; it can be null if
        // you don't want to receive notifications about click events.
        // Impressions and clicks won't be counted if the view is not registered.
        NativeAdSDK.registerTracking(nativeAdResponse, container, adEventListener);
 
        // It's your responsibility to keep a reference to the view
        // and NativeAdResponse object if necessary.
        // Once done with the native ad view, call the following method to
        // unregister that view.
        NativeAdSDK.unRegisterTracking(container);
    }
}
    

Los campos admitidos en aplicaciones nativas

A partir de la versión 5.0 del SDK móvil, la compatibilidad con los activos nativos está alineada con la forma en que se configuran las creatividades nativas en la interfaz de usuario de Xandr.

Si sigues utilizando nativos heredados, tendrás que pasar a un nativo "nuevo" para tus creativos.

La siguiente es una lista completa de los activos nativos admitidos en los SDK.

Recurso ¿Es compatible con la versión anterior a 5.0? ¿Apoyó la publicación 5.0? Ejemplo de API-Usage v5.0+
Imagen, ancho, alto Sí, sí, sí Sí, sí, sí nativeAdResponse.getImage();
nativeAdResponse.getImageSize();
nativeAdResponse.getImageUrl();
Icono+Ancho+Alto Sí, no, no Sí, sí, sí nativeAdResponse.getIcon();
nativeAdResponse.getIconSize();
nativeAdResponse.getIconUrl();
Título nativeAdResponse.getTitle();
Patrocinado por nativeAdResponse.getSponsoredBy();
Texto de cuerpo nativeAdResponse.getDescription();
Desc2 nativeAdResponse.getAdditionalDescription();
Llamada a la acción nativeAdResponse.getCallToAction();
Clasificación, escala Sí, sí Sí, no nativeAdResponse.getAdStarRating();
Me gusta No Sí (solo json) if((nativeAdResponse.getNetworkIdentifier() == NativeAdResponse.Network.APPNEXUS) &&. (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT)) instanceof JSONObject){ JSONObject nativeResponseJSON = (JSONObject) (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT));

String likes = JsonUtil.getJSONString(nativeResponseJSON,"likes"); String downloads = JsonUtil.getJSONString(nativeResponseJSON,"downloads"); String price = JsonUtil.getJSONString(nativeResponseJSON,"price"); String saleprice = JsonUtil.getJSONString(nativeResponseJSON,"saleprice"); String phone = JsonUtil.getJSONString(nativeResponseJSON,"phone"); String address = JsonUtil.getJSONString(nativeResponseJSON,"address"); String displayurl = JsonUtil.getJSONString(nativeResponseJSON,"displayurl"); // To Get clickUrl String clickUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("url"); //To Get clickFallbackUrl String clickFallbackUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("fallback_url"); }
Descargas No Sí (solo json) if((nativeAdResponse.getNetworkIdentifier() == NativeAdResponse.Network.APPNEXUS) &&. (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT)) instanceof JSONObject){ JSONObject nativeResponseJSON = (JSONObject) (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT));

String likes = JsonUtil.getJSONString(nativeResponseJSON,"likes"); String downloads = JsonUtil.getJSONString(nativeResponseJSON,"downloads"); String price = JsonUtil.getJSONString(nativeResponseJSON,"price"); String saleprice = JsonUtil.getJSONString(nativeResponseJSON,"saleprice"); String phone = JsonUtil.getJSONString(nativeResponseJSON,"phone"); String address = JsonUtil.getJSONString(nativeResponseJSON,"address"); String displayurl = JsonUtil.getJSONString(nativeResponseJSON,"displayurl"); // To Get clickUrl String clickUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("url"); //To Get clickFallbackUrl String clickFallbackUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("fallback_url"); }
Precio No Sí (solo json) if((nativeAdResponse.getNetworkIdentifier() == NativeAdResponse.Network.APPNEXUS) &&. (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT)) instanceof JSONObject){ JSONObject nativeResponseJSON = (JSONObject) (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT));

String likes = JsonUtil.getJSONString(nativeResponseJSON,"likes"); String downloads = JsonUtil.getJSONString(nativeResponseJSON,"downloads"); String price = JsonUtil.getJSONString(nativeResponseJSON,"price"); String saleprice = JsonUtil.getJSONString(nativeResponseJSON,"saleprice"); String phone = JsonUtil.getJSONString(nativeResponseJSON,"phone"); String address = JsonUtil.getJSONString(nativeResponseJSON,"address"); String displayurl = JsonUtil.getJSONString(nativeResponseJSON,"displayurl"); // To Get clickUrl String clickUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("url"); //To Get clickFallbackUrl String clickFallbackUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("fallback_url"); }
Precio de venta No Sí (solo json) if((nativeAdResponse.getNetworkIdentifier() == NativeAdResponse.Network.APPNEXUS) &&. (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT)) instanceof JSONObject){ JSONObject nativeResponseJSON = (JSONObject) (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT));

String likes = JsonUtil.getJSONString(nativeResponseJSON,"likes"); String downloads = JsonUtil.getJSONString(nativeResponseJSON,"downloads"); String price = JsonUtil.getJSONString(nativeResponseJSON,"price"); String saleprice = JsonUtil.getJSONString(nativeResponseJSON,"saleprice"); String phone = JsonUtil.getJSONString(nativeResponseJSON,"phone"); String address = JsonUtil.getJSONString(nativeResponseJSON,"address"); String displayurl = JsonUtil.getJSONString(nativeResponseJSON,"displayurl"); // To Get clickUrl String clickUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("url"); //To Get clickFallbackUrl String clickFallbackUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("fallback_url"); }
Phone No Sí (solo json) if((nativeAdResponse.getNetworkIdentifier() == NativeAdResponse.Network.APPNEXUS) &&. (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT)) instanceof JSONObject){ JSONObject nativeResponseJSON = (JSONObject) (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT));

String likes = JsonUtil.getJSONString(nativeResponseJSON,"likes"); String downloads = JsonUtil.getJSONString(nativeResponseJSON,"downloads"); String price = JsonUtil.getJSONString(nativeResponseJSON,"price"); String saleprice = JsonUtil.getJSONString(nativeResponseJSON,"saleprice"); String phone = JsonUtil.getJSONString(nativeResponseJSON,"phone"); String address = JsonUtil.getJSONString(nativeResponseJSON,"address"); String displayurl = JsonUtil.getJSONString(nativeResponseJSON,"displayurl"); // To Get clickUrl String clickUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("url"); //To Get clickFallbackUrl String clickFallbackUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("fallback_url"); }
Dirección No Sí (solo json) if((nativeAdResponse.getNetworkIdentifier() == NativeAdResponse.Network.APPNEXUS) &&. (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT)) instanceof JSONObject){ JSONObject nativeResponseJSON = (JSONObject) (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT));

String likes = JsonUtil.getJSONString(nativeResponseJSON,"likes"); String downloads = JsonUtil.getJSONString(nativeResponseJSON,"downloads"); String price = JsonUtil.getJSONString(nativeResponseJSON,"price"); String saleprice = JsonUtil.getJSONString(nativeResponseJSON,"saleprice"); String phone = JsonUtil.getJSONString(nativeResponseJSON,"phone"); String address = JsonUtil.getJSONString(nativeResponseJSON,"address"); String displayurl = JsonUtil.getJSONString(nativeResponseJSON,"displayurl"); // To Get clickUrl String clickUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("url"); //To Get clickFallbackUrl String clickFallbackUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("fallback_url"); }
Dirección URL de presentación No Sí (solo json) if((nativeAdResponse.getNetworkIdentifier() == NativeAdResponse.Network.APPNEXUS) &&. (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT)) instanceof JSONObject){ JSONObject nativeResponseJSON = (JSONObject) (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT));

String likes = JsonUtil.getJSONString(nativeResponseJSON,"likes"); String downloads = JsonUtil.getJSONString(nativeResponseJSON,"downloads"); String price = JsonUtil.getJSONString(nativeResponseJSON,"price"); String saleprice = JsonUtil.getJSONString(nativeResponseJSON,"saleprice"); String phone = JsonUtil.getJSONString(nativeResponseJSON,"phone"); String address = JsonUtil.getJSONString(nativeResponseJSON,"address"); String displayurl = JsonUtil.getJSONString(nativeResponseJSON,"displayurl"); // To Get clickUrl String clickUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("url"); //To Get clickFallbackUrl String clickFallbackUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("fallback_url"); }
URL del clic No Sí (solo json) if((nativeAdResponse.getNetworkIdentifier() == NativeAdResponse.Network.APPNEXUS) &&. (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT)) instanceof JSONObject){ JSONObject nativeResponseJSON = (JSONObject) (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT));

String likes = JsonUtil.getJSONString(nativeResponseJSON,"likes"); String downloads = JsonUtil.getJSONString(nativeResponseJSON,"downloads"); String price = JsonUtil.getJSONString(nativeResponseJSON,"price"); String saleprice = JsonUtil.getJSONString(nativeResponseJSON,"saleprice"); String phone = JsonUtil.getJSONString(nativeResponseJSON,"phone"); String address = JsonUtil.getJSONString(nativeResponseJSON,"address"); String displayurl = JsonUtil.getJSONString(nativeResponseJSON,"displayurl"); // To Get clickUrl String clickUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("url"); //To Get clickFallbackUrl String clickFallbackUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("fallback_url"); }
Haga clic en la URL de reserva No Sí (solo json) if((nativeAdResponse.getNetworkIdentifier() == NativeAdResponse.Network.APPNEXUS) &&. (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT)) instanceof JSONObject){ JSONObject nativeResponseJSON = (JSONObject) (nativeAdResponse.getNativeElements().get(NativeAdResponse.NATIVE_ELEMENT_OBJECT));

String likes = JsonUtil.getJSONString(nativeResponseJSON,"likes"); String downloads = JsonUtil.getJSONString(nativeResponseJSON,"downloads"); String price = JsonUtil.getJSONString(nativeResponseJSON,"price"); String saleprice = JsonUtil.getJSONString(nativeResponseJSON,"saleprice"); String phone = JsonUtil.getJSONString(nativeResponseJSON,"phone"); String address = JsonUtil.getJSONString(nativeResponseJSON,"address"); String displayurl = JsonUtil.getJSONString(nativeResponseJSON,"displayurl"); // To Get clickUrl String clickUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("url"); //To Get clickFallbackUrl String clickFallbackUrl = JsonUtil.getJSONObject(nativeResponseJSON,"link").getString("fallback_url"); }
URL de privacidad No nativeAdResponse.getPrivacyLink();
Vídeo No nativeAdResponse.getVastXml();
Personalizado No
Contexto No
Texto completo No

OpenRTB Nativo

OpenRTB Native se refiere al uso de la especificación OpenRTB Native Asset en las clases NativeAdRequest y NativeAdResponse, lo que permite solicitudes y respuestas de anuncios más flexibles y estandarizadas. Para obtener más información sobre los estándares de especificación OpenRTB Native 1.2, consulte OpenRTB Native Ads Specification.1.2.

Nota:

OpenRTB Native no está disponible para todos los miembros. Trabaje con el administrador de cuentas o póngase en contacto con el soporte técnico si tiene alguna pregunta.

ORTB en NativeAdRequest

Para usar OpenRTB Native, la aplicación debe especificar activos OpenRTB Native en NativeAdRequest mediante el método setOpenRTBAssets(JSONObject openRTBAssets). El contenido de este campo debe ser una solicitud OpenRTB Native, después del marcado de solicitud OpenRTB Native 1.2.

Java de ejemplo de código para solicitud

NativeAdRequest nativeAdRequest = new NativeAdRequest(context, "PLACEMENT_ID");
String ortbJSONString = "{\"ver\":\"1.2\",\"assets\":[{\"id\":1,\"required\":1,\"title\":{\"len\":300}},{\"id\":2,\"required\":1,\"data\":{\"type\":2}},{\"id\":3,\"required\":1,\"data\":{\"type\":1}},{\"id\":4,\"required\":1,\"image\":{\"type\":3}},{\"id\":5,\"required\":0,\"data\":{\"type\":555,\"len\":45}}]}";
nativeAdRequest.setOpenRTBAssets(new JSONObject(ortbJSONString));

Kotlin de ejemplo de código para solicitud


var nativeAdRequest = NativeAdRequest(context, "PLACEMENT_ID")
val ortbJSONString = "{\"ver\":\"1.2\",\"assets\":[{\"id\":1,\"required\":1,\"title\":{\"len\":300}},{\"id\":2,\"required\":1,\"data\":{\"type\":2}},{\"id\":3,\"required\":1,\"data\":{\"type\":1}},{\"id\":4,\"required\":1,\"image\":{\"type\":3}},{\"id\":5,\"required\":0,\"data\":{\"type\":555,\"len\":45}}]}"
nativeAdRequest.openRTBAssets = JSONObject(ortbJSONString);

Nota:

La aplicación no necesita especificar la matriz eventtrackers. El SDK rellena automáticamente la matriz eventtrackers con los valores que admite. Incluso si la aplicación proporciona un valor, el SDK lo invalidará.

ORTB en NativeAdResponse

ORTB en respuesta corresponde al JSON nativo ORTB sin procesar, que se expone a la aplicación mediante el método JSONObject getOpenRTBNative() público en la clase NativeAdResponse. Al igual que la solicitud, la respuesta JSONObject seguirá el marcado de respuesta OpenRTB Native 1.2, consulte OpenRTB Native Ads Specification.1.2 para obtener más detalles.

Además de exponer la respuesta nativa de ORTB sin procesar JSONObject a través de getOpenRTBNative(), el SDK también analiza y pone a disposición activos de respuesta nativos de ORTB estándar (img, title, video y data) utilizando métodos como getTitle(), getDescription(), getImageUrl(), getImage(), getImageSize(), getIconUrl(), getIcon(), getIconSize(), getCallToAction(), getAdStarRating(), getSponsoredBy(), getVastXml() y getPrivacyLink(). El SDK también controla automáticamente la impresión, la visibilidad y el seguimiento de clics.

Nota:

La aplicación debe registrar la vista en la que se representa el anuncio nativo con el SDK. El SDK se encargará del seguimiento de las impresiones, los clics y la visibilidad. La aplicación no recibirá eventtrackers, imptrackers, jstracker o clicktrackers en el JSONObject de respuesta nativa de ORTB.

Java de ejemplo de código para respuesta

@Override
public void onAdLoaded(NativeAdResponse nativeAdResponse) {

    // Network type Network.APPNEXUS_ORTB indicates the response is ORTB
    if (nativeAdResponse.getNetworkIdentifier() == NativeAdResponse.Network.APPNEXUS_ORTB) {
        JSONObject ortbNativeResponseJSON = nativeAdResponse.getOpenRTBNative();

        // App has the option to either
        // 1. Use the parsed title, description, etc., which the SDK readily makes available
        // and dip into the ORTB Native response JSON for non-parsed/custom values
        // OR
        // 2. Handle all the ORTB Native response JSON response parsing in the app

        // Accessing title, description etc using the getters exposed in
        // NativeAdResponse class
        String title = nativeAdResponse.getTitle();
        String description = nativeAdResponse.getDescription();
        String imageUrl = nativeAdResponse.getImageUrl();
        NativeAdResponse.ImageSize imageSize = nativeAdResponse.getImageSize();
        
        
        // Parsing ORTB Native resposnse JSON
        // Extract "assets" array
        JSONArray assetsArray = ortbNativeResponseJSON.getJSONArray("assets");
        for (int i = 0; i < assetsArray.length(); i++) {
            JSONObject asset = assetsArray.getJSONObject(i);
            // This id will match the id provided in the request.
            // This id is essential for matching the various data assets in the request
            // with the response.            
            int id = asset.getInt("id");
            System.out.println("Asset ID: " + id); 

            // Check for "title"
            if (asset.has("title")) {
                String assetTitle = asset.getJSONObject("title").getString("text");
                System.out.println("Title: " + assetTitle);
            }

            // Check for "data"
            if (asset.has("data")) {
                String data = asset.getJSONObject("data").getString("value");
                System.out.println("Data: " + data);
            }

            // Check for "image"
            if (asset.has("image")) {
                JSONObject image = asset.getJSONObject("image");
                String url = image.getString("url");
                int width = image.getInt("w");
                int height = image.getInt("h");
                System.out.println("Image URL:"+url+",Width:"+width+",Height:"+height);
            }
        }
    }
}

Kotlin de ejemplo de código para la respuesta


override fun onAdLoaded(nativeAdResponse: NativeAdResponse) {

    // Network type Network.APPNEXUS_ORTB indicate the response is ORTB
    if(nativeAdResponse.networkIdentifier == NativeAdResponse.Network.APPNEXUS_ORTB) {
        var ortbNativeResponseJSON = nativeAdResponse.openRTBNative

        // App has the option to either
        // 1. Use the parsed title,description etc which the SDK readily makes available
        // and dip into the ORTB Native response JSON for non-parsed/custom values
        // OR
        // 2. Handle all the ORTB Native response JSON response parsing in the app

        // Accessing title, description etc using the getters exposed in
        // NativeAdResponse class
        nativeAdResponse.title
        nativeAdResponse.description
        nativeAdResponse.imageUrl
        nativeAdResponse.imageSize


        // Parsing ORTB Native resposnse JSON
        // Extract "assets" array
        val assetsArray = ortbNativeResponseJSON.getJSONArray("assets")
        for (i in 0 until assetsArray.length()) {
            val asset = assetsArray.getJSONObject(i)
            // This id will match the id provide in request,
            // This id is essential for matching the various data assets in req with response            
            val id = asset.getInt("id")
            println("Asset ID: $id") 

            // Check for "title"
            if (asset.has("title")) {
                val title = asset.getJSONObject("title").getString("text")
                println("Title: $title")
            }

            // Check for "data"
            if (asset.has("data")) {
                val data = asset.getJSONObject("data").getString("value")
                println("Data: $data")
            }

            // Check for "image"
            if (asset.has("image")) {
                val image = asset.getJSONObject("image")
                val url = image.getString("url")
                val width = image.getInt("w")
                val height = image.getInt("h")
                println("Image URL: $url, Width: $width, Height: $height")
            }
        }
    }

Ejemplo: Estructura JSONObject de respuesta nativa ORTB en NativeAdResponse


 {
       "ver": "1.2",
       "assets": [
      {
          "id": 1,
          "title": {
              "text": "Sample Title here."
          }
       },{    
          "id": 2,
          "data": {
              "value": "Sample description text here."
           }
      }, {
          "id": 3,
          "data": {
              "value": "Sample Sponsored by text here."
          }
      }, {
          "id": 4,
          "image": {
              "url": "https://sample.img.url/here.jpg",
              "w": 123,
              "h": 234
          }
      }, {
          "id": 5,
          "data": {
              "value": "Sample disclaimer value here."
          }
      }
   ],
  // remaining ortb native 1.2 response fields would be here;
  // ie for link,privacy etc if available
}