2017-03-05 27 views
0

我想Java接口轉換成JSON模式,但它給NullPointerException異常錯誤Java接口轉換成JSON模式

public interface Contributors { 

public List<Contributor> contributors(); 

public interface Contributor { 

    public String name(); 

    public String contributorUrl(); 

    public List<String> roles(); 

} 

} 

編輯2: 我正在以下的輸出:

{"type":"object","$schema":"http://json-schema.org/draft-04/schema#"} 

編輯3:

以下是SchemaGeneratorTest的代碼

import com.fasterxml.jackson.core.JsonProcessingException; 
import com.fasterxml.jackson.databind.JsonNode; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.databind.SerializationFeature; 
import com.github.reinert.jjschema.exception.TypeException; 
import com.github.reinert.jjschema.v1.JsonSchemaFactory; 
import com.github.reinert.jjschema.v1.JsonSchemaV4Factory; 

public class SchemaGeneratorTest { 
    private static ObjectMapper mapper = new ObjectMapper(); 
    public static final String JSON_$SCHEMA_DRAFT4_VALUE = "http://json-schema.org/draft-04/schema#"; 
    public static final String JSON_$SCHEMA_ELEMENT = "$schema"; 

    static { 
     // required for pretty printing 
     mapper.enable(SerializationFeature.INDENT_OUTPUT); 
    } 

    public static void main(String[] args) throws JsonProcessingException, TypeException { 

     JsonSchemaFactory schemaFactory = new JsonSchemaV4Factory(); 
     schemaFactory.setAutoPutDollarSchema(true); 
     JsonNode productSchema = schemaFactory.createSchema(Contributors.class); 
     System.out.println(productSchema); 
    } 
    } 
+0

您是否編寫SchemaGeneratorTest?如果是這樣,請發佈該代碼。 – Nulano

+0

你嘗試過調試嗎? NullPointerException很容易找到。 – 2017-03-05 12:14:42

+0

@Nulano更新。 –

回答

1

您正在使用的庫僅報告模式中的字段和獲取者。重命名你的方法開始與get

public interface Contributors { 
    public List<Contributor> getContributors(); 
} 

public interface Contributor { 
    public String getName(); 
    public String getContributorUrl(); 
    public List<String> getRoles(); 
} 

編輯:如果你不能修改界面,您可以使用此代碼來破壞「get」字符串,並讓它繼續打印的所有方法。請不要在實際的生產代碼中使用它,因爲您會造成很大的麻煩。

public class Test { 

    private static boolean isCorrupted() { 
     return "haha".startsWith("get"); 
    } 

    public static void main(String[] args) throws Exception { 
     String get = "get"; 
     Field value = String.class.getDeclaredField("value"); 
     value.setAccessible(true); 
     value.set(get, new char[]{}); 
     System.out.println(isCorrupted()); // prints true 
    } 

} 
+0

嗨@nulano不幸的是我無法觸及界面合同。任何其他方式做到這一點,而不改變合同? –

+1

@ArchitMaheshwari不幸的是,沒有修改'JsonSchemaGenerator'就沒有辦法做到這一點。您可以嘗試在github上打開一個功能請求問題(沿着 - 「添加選項將所有方法視爲getter」)。這是一個很好的例子,爲什麼getters應該總是以'get'或'is'作爲前綴。實際上,如果你真的想,你可以用反射來修改它,但我認爲這超出了這個SO問題的範圍._ – Nulano

+0

是的,它似乎還沒有被支持。你可以提供任何指針來反射轉換它,以便下列庫可用於我的目的。謝謝您的幫助。 –