Print JSON to screen as a block of text in unity

2019-08-26 16:53发布

问题:

I am using unity3d and I have a JSON object. I am able to access each member using ob.name and so on but I am looking to get this deserialized block to be printed on my screen during run time.Similar to a search result , so I get the JSON as a result of search and I want to display it on my screen.I get errors that I cannot print the object because I used (ob.name)toString(); I am not sure how to display this during run time on the screen.

ObjR rs = JsonUtility.FromJson<ObjR>(jsonString);
//so now I want to print to screen each element of rs.How do I do that during runtime.

EDIT : I am able to see on Debug.Log , I just need to dynamically print them on screen.Please note , the size or number of results is on runtime and will vary.Any help is appreciated.So I found this and now I get it on the screen. http://wiki.unity3d.com/index.php/DebugConsole.Can anybody help on how I can make each respond to click events ?

var client = new RestClient(Url);
var req = new RestRequest(UrlEndpoint, Method.GET)
            .AddParameter("apikey", apiKey)
            .AddParameter("q", query)

    // Perform the search and obtain results
var resp = client.Execute(req);
var search = JsonConvert.DeserializeObject<dynamic>(resp.Content);

// Print the number of results
Console.WriteLine("Number of hits: " + search["hits"]);
Debug.Log(search["hits"] + " ");
foreach (var result in search["results"])
{
    var part = result["item"];
    // want to print to screen each item and mpn
    //Debug.Log(part["brand"]["name"] + " " + part["mpn"]);
    //what i tried/ string hits = search["hits"].ToString();//error

    //expected type object and found string
    GUILabel(float,float,needed string here);
}

回答1:

The problem is that when you use var search = JsonConvert.DeserializeObject<dynamic>(resp.Content);, you are not de-serializing it to a specific Object and it is hard to print your json.

If you know what the Json looks like then use this to convert it to an Object that you can easily use to display the Json on the screen. Note that you must remove { get; set; } and add [Serializable] to the top of each generated class as described here.

With those generated classes, you can convert the received Json to Object

//Convert Json to Object so that we can print it
string yourJsonFromServer = resp.Content;//Replace with Json from the server
RootObject rootObj = JsonUtility.FromJson<RootObject>(yourJsonFromServer);

Now, concatenate all the strings you need to display.

string dispStr;
dispStr = "__class__: " + rootObj.__class__ + "\r\n";
dispStr = dispStr + "mpn:" + rootObj.mpn + "\r\n";
dispStr = dispStr + "uid:" + rootObj.uid + "\r\n";

//manufacturer info
dispStr = "Manufacturer __class__: " + rootObj.manufacturer.__class__ + "\r\n";
dispStr = "Manufacturer homepage_url: " + rootObj.manufacturer.homepage_url + "\r\n";
dispStr = "Manufacturer name: " + rootObj.manufacturer.name + "\r\n";
dispStr = "Manufacturer uid: " + rootObj.manufacturer.uid + "\r\n";

Finally, use the Text component to display them. One Text component is enough for this. Just use "\r\n" to separate them:

public Text infoText;
...
infoText.horizontalOverflow = HorizontalWrapMode.Overflow;
infoText.verticalOverflow = VerticalWrapMode.Overflow;
infoText.text = dispStr;

For List or Array items, you can just use for loop to over over and display them.

string dispStr = "";
for (int i = 0; i < rootObj.offers.Count; i++)
{
    dispStr = dispStr + "SKU: " + rootObj.offers[i].sku + "\r\n";
    dispStr = dispStr + "REGION: " + rootObj.offers[i].eligible_region + "\r\n\r\n\r\n";
}
infoText.text = dispStr;

Complete Example:

public Text infoText;

void Start()
{
    //Convert Json to Object so that we can print it
    string yourJsonFromServer = resp.Content;//Replace with Json from the server
    RootObject rootObj = JsonUtility.FromJson<RootObject>(yourJsonFromServer);

    string dispStr;

    dispStr = "__class__: " + rootObj.__class__ + "\r\n";
    dispStr = dispStr + "mpn:" + rootObj.mpn + "\r\n";
    dispStr = dispStr + "uid:" + rootObj.uid + "\r\n";

    //Example, Show manufacturer info
    dispStr = "Manufacturer __class__: " + rootObj.manufacturer.__class__ + "\r\n";
    dispStr = "Manufacturer homepage_url: " + rootObj.manufacturer.homepage_url + "\r\n";
    dispStr = "Manufacturer name: " + rootObj.manufacturer.name + "\r\n";
    dispStr = "Manufacturer uid: " + rootObj.manufacturer.uid + "\r\n";

    //Display
    infoText.horizontalOverflow = HorizontalWrapMode.Overflow;
    infoText.verticalOverflow = VerticalWrapMode.Overflow;
    infoText.text = dispStr;
}

Generated classes:

[Serializable]
public class Brand
{
    public string __class__;
    public string homepage_url;
    public string name;
    public string uid;
}

[Serializable]
public class Manufacturer
{
    public string __class__;
    public string homepage_url;
    public string name;
    public string uid;
}

[Serializable]
public class Prices
{
    public List<List<object>> USD;
    public List<List<object>> INR;
}

[Serializable]
public class Seller
{
    public string __class__;
    public string display_flag;
    public bool has_ecommerce;
    public string homepage_url;
    public string id;
    public string name;
    public string uid;
}

[Serializable]
public class Offer
{
    public string __class__;
    public string _naive_id;
    public string eligible_region;
    public int? factory_lead_days;
    public object factory_order_multiple;
    public int in_stock_quantity;
    public bool is_authorized;
    public bool is_realtime;
    public string last_updated;
    public int? moq;
    public object octopart_rfq_url;
    public object on_order_eta;
    public int? on_order_quantity;
    public object order_multiple;
    public object packaging;
    public Prices prices;
    public string product_url;
    public Seller seller;
    public string sku;
}

[Serializable]
public class RootObject
{
    public string __class__;
    public Brand brand;
    public Manufacturer manufacturer;
    public string mpn;
    public string octopart_url;
    public List<Offer> offers;
    public List<string> redirected_uids;
    public string uid;
}


回答2:

If you want to make some debug output with this json - it will be easier to use GUI.Label. It's easy to setup and you can manage the size of the label according to the number of lines or number of characters in your string. But it's definitely not for production, because of bad performance.

Another simple way is to create Unity UI Canvas and add a Panel with Text element. Text element has a Best Fit property which allows you to set a minimum and maximum font size for the label. So the size of the font will be calculated automatically to make the text fit the size of the Text element. In order to receive click events on the Text element you can also add a Button element.